Conditional statements are used when we want to perform an action based on a condition. For instance, I can check if it's raining to decide whether to stay home or go out.
Conditional statements have a body structure (wrapped in between curly braces {} ). PHP keywords for condional statements are if, else, else if.
if/else
Decisions in PHP take the following form:
<?php #if-statements.php
if (condition) { //Code to be executed if condition is true } else { //Alternative code }
?>
The else part of the above is optional. A condition is an expression that can be evaluated to true or false. PHP treats 0 and the empty string as false, and everything else as true. Here is some example code:
<?php #if-statements.php
$name = "Bill"; if($name == "Bill") { echo "Hi Bill!"; } else { echo "Hello person-who-is-not-Bill"; }
?>
IF statements can be chained together using ELSEIF :
<?php #if-statements.php
$width = 100;
$height = 20;
if($width > $height) { echo "The object is wider than it is high"; } elseif ($width == $height) { echo "The object has similar width and height"; } else { echo "The object is higher than it is wide"; }
?>
An Example:
<?php #if-statements.php //declare a variable and assign it a value $day = "wed"; if($day == "wed") { echo "Today is wednesday"; } else { echo "Today is not wednesday... Is it thursday?"; } ?>
Click here to read about switch statements.