PHP Conditional Statements
This video was created by Dani Krossing
Conditional statements control the flow of a program by executing code only when certain conditions are met. Therefore, they are a fundamental part of a program's control flow.
The control flow is the order in which a computer executes statements in a script. When code is run, each statement is executed from top to bottom, unless there statements that alter the control flow, like conditionals statements or loops.
PHP has two main conditional statements, the if
statement and the switch
statement.
if
The most common and most used conditional statement is the if
statement. The if
statement determines whether or not to execute a block of code, by evaluating an expression. If the expression evaluates to TRUE
the block of code will execute, otherwise, it will not.
<?php
$a = 4;
$b = 3;
// check if a is greater than b
if ($a > $b) {
echo "a is greater than b"; // this will execute
}
// check if a is less than b
if ($a < $b) {
echo "a is less than b"; // this will not execute
}
?>
else
The else
statement extends the if
to execute a statement when the expression of the if
statement evalutates to false
.
<?php
$a = 4;
$b = 3;
// check if a is less than b
if ($a < $b) {
echo "a is less than b";
} else {
echo "a is not less than b"; // this will execute
}
?>
elseif
The elseif
statement ig used in conjunction with an if
statement to provide an alternative path if the if
statement's condition evaluated to FALSE
. The elseif
statement is tied to a specified condition, similar to the if
statement, and will only execute if the condition evaluates to true. There is no limit to the number of elseif
statement, but the else
statement must always be the last in the line.
NOTE
In an if / elseif / else
structure, conditions are only evaluated if the previous condition was FALSE
.
<?php
$a = 3;
$b = 4;
// comparing a to b
if ($a > $b) {
echo "a is larger than b";
} elseif ($a < $b) {
echo "a is smaller than b";
} else {
echo "a is equal to b";
}
?>
switch
The switch
statement is an alternative to an if
statement. With the switch
statement you take a single variable or expression and compare it against a list of possible values, checking if they are equal.
When a switch
statement finds a case that matches, it will execute that case's statement and then "fallthrough" all the remaining cases until it reaches the end of the switch
block OR it finds a break
statement. This is why in almost all cases, it is important to add a break
at the end of each case.
The default
case is to match anything that wasn't matched by other cases. It is the equivalent of the else
statement.
<?php
$a = 3;
switch ($a) {
case 0:
echo "a equals 0 <br>";
break;
case 1:
echo "a equals 1 <br>";
break;
case 2:
echo "a equals 2 <br>";
break;
case 3:
echo "a equals 3 <br>";
break;
default:
echo "a is not 0, 1, 2, or 3 <br>";
break;
}
?>