PHP 7.x — P24: If Statement

The if statement is probably the first piece of code that you wrote. “If” statements are conditional statements, meaning that if the expression that they’re evaluating is true, the if statement will allow for the execution of the expressions inside of the if statement body.
The anatomy of the if statement looks like this:
<?phpif ( boolean expression ) {
expressions in body
}?>
The if statement starts with the word if, followed by an expression enclosed by parentheses. The expression will evaluate to either true or false. If the expression evaluates to true, the expressions inside the if statement body (normally surrounded by curly braces) will be executed.
Let’s look at a quick example. We are going to guarantee that the expression inside the if statement evaluates to true by passing the boolean value true to it.
<?phpif ( true ) {
echo "Donkey";
}?>
The code above will output Donkey since the boolean expression inside the if statement evaluates to true. Any type of expression that evaluates to true or false can be placed inside the conditional.
<?php$a = 10;if ( $a > 5 ) {
echo "Math";
}?>
PHP evaluates the if statement above as follows:
- PHP sees the keyword if.
- It looks for the opening parentheses.
- It evaluates the expression inside the parentheses. Is the value stored in $a greater than 5? In other words, is 10 greater than 5? Yes. So, the expression is true.
- Since the expression is true, PHP looks inside of the if statement body and finds an echo statement. It echoes out Math.
You can also compare strings inside of the boolean expression. As was mentioned earlier, the expression just needs to evaluate to true or false.
<?php$word = "confused";if ( $word == "confused" ){
echo "Bumfuzzle";
}?>
You can also use the negation operator to flip the value of the conditional statement. With the negation operator, if the value is true, the negated value will be false; if the value is false, the negated value will be true.
When would you need to use the negation operator? Sometimes you need to evaluate the expression inside of the if statement when the conditional evaluates to false. In that case, you can append the ! operator and flip the false to true. Remember, the only way for the statements to get executed inside of the if statement is if the condition evaluates to true.
<?php$definitelyfalse = false;if ( !$definitelyfalse ) {
echo "Opposite of false is true";
}?>
The if statement body can contain multiple expressions.
<?phpif ( true ) {
$a = 3;
$b = 5;
$c = $a + $b; echo $c;}?>
If there is only one expression inside of the if-statement body, curly braces may be omitted.
<?php$oneExpression = true;if ( $oneExpression)
echo "One Expression";?>
Curly braces don’t have to be used even with multiple expressions. PHP offers alternate syntax with colon/endif.
<?php$time = 6;if ( $time >= 6 && $time < 9 ):
echo "Early Morning";
endif;?>