PHP Conditional Statements
Programs constantly have to make decisions: if the user is logged in, show one thing; if not, show another. Conditional statements are how you tell PHP to choose between different actions.
PHP gives you these options:
ifstatement - runs a piece of code only when a condition is trueif...elsestatement - runs one piece of code when a condition is true and a different piece when it is falseif...elseif...elsestatement - chooses between different pieces of code when there are more than two conditionsswitchstatement - picks one block out of many to run
The if Statement
The simplest decision is an if: when its condition is true, the code inside the braces runs, and otherwise PHP skips it.
If Statement
Since 5 is greater than 3, the condition is true and the message is displayed:
Output: PHP script
<?php
if (5 > 3) {
echo "5 is greater than 3";
}
?>
Syntax
An if statement is written like this:
<?php
if (condition) {
// code to be executed if condition is true;
}
?>
Indentation
Indenting the code inside an if block is optional as far as PHP is concerned. Do it anyway, since it is considered good practice and makes the structure much easier to read.
Indentation Example
The echo line below is indented to show that it belongs to the if block:
Output: PHP script
<?php
$x = 10;
if ($x > 0) {
echo "$x is a positive number";
}
?>
Multiple Conditions
A single if can test several conditions at once. Join them with the && or || operators, and add as many as you need:
And Operator
Both checks have to pass here: $a must be above $b and, at the same time, below $c:
Output: PHP script
<?php
$a = 200;
$b = 33;
$c = 500;
if ($a > $b && $a < $c) {
echo "Both conditions are true";
}
?>
Or Operator
One passing check is enough with OR. Here $a would need to be 2 or 3, but it is 5, so the else block runs:
Output: PHP script
<?php
$a = 5;
if ($a == 2 || $a == 3) {
echo "a is 2 or 3";
} else {
echo "a is not 2 and not 3";
}
?>