else extends an if statement to execute a statement in case the expression in the if statement evaluates to FALSE. By using else, you can specify statements when the result of expression is both true and false. The else statement does not have expression and cannot be used without if statement.
Structure of if-else
Syntax | Description |
---|---|
if(expr) stmt1; else stmt2; |
1) executes stmt1 if expr is TRUE 2) executes stmt2 if expr is not TRUE |
<?php
$var1 = $var2 = 2;
if($var1 == $var2) // expression is FALSE
echo "var1 and var2 are equal";
else
echo "var1 and var2 are not equal"; // statement will be executed
?>
[result]
var1 and var2 are equal
<?php
$var1 = $var2 = 1;
$var3 = 2;
if($var1 > $var2) // expression is FALSE
echo "var1 and var2 are equal";
else
{
if($var1 > $var3) // expression is FALSE
echo "good";
else
echo "bad"; // statement will be executed
}
?>
[result]
bad