The else statement provides a default block of code that executes if the condition returned is FALSE. It cannot used by itself. It has to be together with the if statement.
if (conditional expression) {
code to be executed if condition is true;
}
else {
code to be executed if condition is false;
}
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="EN" lang="EN"> <head> <title>PHP</title> <meta Name="Author" Content="Hann So"> </head> <body> <p> <?php // compare a string $wheather = "sunny"; if ($wheather == "bad") { echo "Well today is not a $wheather day.<br />"; } else { echo "Well I like a $wheather day.<br />"; } // use logical operators $temperature = 60; if ($temperature > 74 && $temperature < 80) { echo "We have a good temperature with $temperature degrees.<br />"; } else { echo "$temperature degrees is not a good day.<br />"; } ?> </p> </body> </html> |
You can build more complicated processes by nesting if statements within each other.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="EN" lang="EN"> <head> <title>PHP</title> <meta Name="Author" Content="Hann So"> </head> <body> <p> <?php $tireqty = 15; $oilqty = 3; $sparkqty = 3; $totalqty = $tireqty + $oilqty + $sparkqty; if ($totalqty == 0) { echo "You did not order anything.<br />"; } else { if ($tireqty>0) echo "$tireqty tires<br />"; if ($oilqty>0) echo "$oilqty bottles of oil<br />"; if ($sparkqty>0) echo "$sparkqty spark plugs<br />"; } ?> </p> </body> </html> |