PHP Decision Making
What is decision making ? Think you need to check a number equals to another number.
$a = 10;
$b = 20;
You know these two variables are not equal. In programming how do you use it. When you make a decission that decision can be true or false we already know that there is data type called 'boolen'. that data type hold true or false only. if the '$a ' equals to '$b' the out put should be true. but in my example '$a' not equals to '$b' so the output should be false.
The IF..ELSE Statement
We can use to make a decision 'if else' statements. if ( checking condition ). Lets do a example.
$a = 10
$b = 20
if($a == $b){
echo "a equals to b";
}else{
echo "a not equals to b";
}
in here we use ' == ' sign. When we use ' = ' sign we spell it as 'equal'. so When we use ' ==' sign we spell that ;equal equal to' . Then the out put will be a boolean value (true or false) because we need to use boolean value for the if statement's condition. When we use comparison operators out put will be a boolean value(check php-operators).
ELSEIF Statement
If we need to check multiple cases we can use 'elseif ' statement.
$a = 10;
$b = 20;
$c = 20;
if($a == $b){
echo "a equals to b";
}elseif($a == $c){
echo "a equals to c";
}else{
echo "a not equals to b and a not equals to c ";
}
The Switch Statement
We also can use switch statement for multiple case decision make. Above example using switch statement.
$a = 10;
$b = 20;
$c = 20;
switch($a){
case $b:
echo "a equals to b";
break;
case $c:
echo "a equals to c";
default:
echo "a not equals to b and a not equals to c ";
}
in switch statement we can put the variable which need to check in side brackets. in our exaple it looks like this 'switch($a)' because we need to check variable '$a'. Then in 'case' statement can put checking values for variable '$a'. In our example 'case $b' and 'case $c'. Which means check variable $a 's value equals to variable $b if that is not equals then check variable $c if that also not equals then 'default' statement executes.
Thats it we done it. !. Lets do a example.
<!DOCTYPE >
<html>
<head>
<title>Php decision</title>
</head>
<body>
<?php
$a = 10;
$b = 20;
$c = 10;
//print the variables
echo "a is ". $a. "<br />";
echo "b is ". $b. "<br />";
echo "c is ". $c. "<br />";
//if else statement
echo "<h2>if else statement </h2> ";
if($a == 10){
echo "a is ten ! <br />";
}else{
echo "a is not ten <br />";
}
//end if else statement
//elseif statement
echo "<h2>elseif statement </h2> ";
if($a == $b){
echo "a equals to b <br />";
}elseif ($a == $c) {
echo "a equals to c <br />";
}else{
echo "a is not equals to b or c <br />";
}
//end elseif statement
//switch statement
echo "<h2>switch statement </h2> ";
switch ($a) {
case $b:
echo "a equals to b <br />";
break;
case $c:
echo "a equals to c <br />";
break;
default:
# code...
break;
}
?>
</body>
</html>
No comments:
Post a Comment
Note: Only a member of this blog may post a comment.