if-elseif-else Statement
Explore how the if-elseif-else statement in PHP lets you check multiple conditions and execute different code paths. Understand its syntax and behavior through examples to effectively make decisions in your PHP programs.
We'll cover the following...
Conditionals in PHP with else if
The if-elseif-else statement is the more complex form of the if-else block. It is used when you need to check multiple conditions and there’s a different action that needs to be performed for each condition. In PHP, this is a common way to write conditionals when a program has more than two possible paths. Here, the else block is replaced by one or more else if conditions, followed by an optional ending else block.
Syntax
Let’s take a look at an example below to better understand the concept of nested ifs.
Explanation
-
All the statements in the code above will run in order from top to bottom until a condition has been met.
-
In line 4 we check if
scoreis greater than 100. -
In line 7 we check if
scoreis less than 0. -
In line 10 we check if
scoreis greater than or equal to 50. -
In line 13 the
elsecondition will execute if all the conditions above evaluate to false.
Changing Score value
-
If you change the
scoreto 110 the output displayed would be Error: the score is greater than 100! -
If you change the
scoreto -20 the output displayed would be Error: the score is less than 0! -
If you change the
scoreto 48 the output displayed would be: Fail!
As useful as these else if conditions are, there’s an easier way to write conditionals in PHP, i.e., using the switch statements which we will discuss in detail in the next lesson!