if (expression) {
statements or block or statements
}
The expression is evaluated by the if statement return a boolean value (i.e. either true or false).![]() |
If we have two variable $x and $y to be evaluated in if condition then, if($x == $y) : returns true if x is equal to y if($x != $y) : returns true if x is not equal to y if($x < $y) : returns true if x is less than y if($x > $y) : returns true if x is greater than y if($x <= $y) : returns true if x is less than or equal to y if($x >= $y) : returns true if x is greater than or equal to y |
<?php
$a = 20;
$b = 20;
$c = 20;
if($a == $b) // a is equal to b , hence returns boolean true
{
echo "Value of a = ".$a."<br>";
echo "Value of b = ".$b."<br>";
echo "a is equal to b";
}
if($a == $c) // a is not equal to b , hence returns boolean false
{
echo "Value of a = ".$a."<br>";
echo "Value of c = ".$c."<br>";
echo "a is equal to c";
}
?>
In the above example value of a and b is equal hence first if condition returns TRUE, so the if block is being executed. Where as a and c are not equal thus if block two is not executed.Output
Value of a = 20 Value of b = 20 a is equal to b
if (expression) {
statement or block or statements
}
else {
statements or block or statements
}
<?php $a = 20; $b = 20; $c = 20;
/* a is equal to b, hence returns boolean true and "if" block is executed */
if($a == $b) { echo "Value of a = ".$a."<br>"; echo "Value of b = ".$b."<br>"; echo "a is equal to b<br><br>"; } else { echo "Value of a = ".$a."<br>"; echo "Value of b = ".$b."<br>"; echo "a is not equal to b<br><br>"; }
/* a is not equal to b , hence returns boolean false and "else" block is executed */
if($a == $c) { echo "Value of a = ".$a."<br>"; echo "Value of c = ".$c."<br>"; echo "a is equal to c"; } else { echo "Value of a = ".$a."<br>"; echo "Value of c = ".$c."<br>"; echo "a is not equal to c<br>"; } ?>
The if-else statement just improvises the if statement example. If a statement returns boolean false then now the else block is being executed.Output
Value of a = 20 Value of b = 20 a is equal to b Value of a = 20 Value of c = 20 a is equal to c
![]() |
If we have only one statement in if or else condition statements, we do not require braces e.g. if(2 > 5) echo "2 > 5 : true"; else echo "2 > 5 : false"; |
<?php
$day=5;
if($day == 1)
echo "Its a Monday!";
elseif ($day == 2)
echo "Its a Tuesday!";
elseif ($day == 3)
echo "Its a Wednesday!";
elseif ($day == 4)
echo "Its a Thursday!";
elseif ($day == 5)
echo "Its a Friday!";
elseif ($day == 6)
echo "Its a Saturday!";
else {
echo "Its a Sunday!!<br>";
echo "Its a Holiday!!<br>";
}
?>
Output
Its a Friday!