Search⌘ K
AI Features

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.

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.

PHP
<?php
$score = 50; //change the value of score to see other results
if ($score > 100)
{ // If score is greater than 100
echo "Error: the score is greater than 100!\n";
}
else if ($score < 0)
{ // Else If score is less than 0
echo "Error: the score is less than 0!\n";
}
else if ($score >= 50)
{ // Else if score is greater or equal to 50
echo "Pass!\n";
}
else
{ // If none above, then score must be between 0 and 49
echo "Fail!\n";
}
?>

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 score is greater than 100.

  • In line 7 we check if score is less than 0.

  • In line 10 we check if score is greater than or equal to 50.

  • In line 13 the else condition will execute if all the conditions above evaluate to false.

Changing Score value

  • If you change the score to 110 the output displayed would be Error: the score is greater than 100!

  • If you change the score to -20 the output displayed would be Error: the score is less than 0!

  • If you change the score to 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!