Conditional Statements PHP
Conditional statements are most often used to compare two or more value either true or false. conditional statements are used with comparison and logical operators.
There are two types of conditional statements:
1) if...elase statement
2) Switch statement
If Statement
If statement is very famous statement in PHP and other programming languages.
This statement is used when a condition is true and another condition
is false
if (condition)
statement
else
statement;
if (condition)
statement
elseif (condition)
statement
else
statement;
Example
<body>
<?php
$a=5;
$b=10;
if ($a<=$b)
echo "Values are not equal!";
else
echo "Values are equal";
?>
</body>
</html>
In this code you can see if $a variable equal to $b then show output "values are not equal" otherwise executes else statement ("values are false"). You can also use other comparison operators as well as you can use if .. else statement with logical operators
<body> <?php
$day1="Sat";
$day2="Sun"; if(($day1=="Sat")||($day2=="Sub")){
echo "These are holidays";
}else{
echo "These are Working days";
}
?>
</body>
</html>
<body>
<?php
if($operator=="+"){
$result = $operand1 + $operand2;
else if($operator=="-"){
$result = $operand1 - $operand2;
}
else if($operator=="*"){
$result = $operand1 * $operand2;
}
else if($operator=="/"){
$result = $operand1 / $operand2;
}
else
{
print "unknown operator";
}
?>
</body>
</html>
Switch Statement
If statement can contain as many elseif clauses as you need, but including many
of these clauses can often create complex code, alternative is of if else statement
is available. switch is a conditional statement that can have multiple branches
in a much more compact format.
case constant:
statements;
...
case constant:
statements;
default:
statements;
}
case '+': $result = $operand1 +$operand2;
break;
case '-': $result = $operand1 - $operand2;
break;
case '*': $result = $operand1 * $operand2;
break;
case '/': $result = $operand1 / $operand2;
break;
default:
print "unknown operator:";break;
}
Note: For better understanding, practices if else statement with all comparison and logical operators, then you can better understand.
