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:
1 2 3 4 5 6 7 8 9 |
<?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:
1 2 3 4 5 6 7 8 9 10 11 |
<?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 :
1 2 3 4 5 6 7 8 9 |
<?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:
1 2 3 4 5 6 7 8 9 10 11 12 13 |
<?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.