PHP Elseif Statement Tutorial

The PHP elseif statement takes us a step farther than the regular PHP if else statement. It allows us to check as many conditions as we like and then take the appropriate action for any condition that is met.

Suppose we wanted to check for the occurrence of any of 10 possible conditions. The regular if-else statement would not work well as that can only handle 2 scenarios; whether the condition is true or the condition is false.

When it comes to checking multiple conditions, the PHP elseif statement shows its power. Have a look at the tutorial below.

PHP Elseif Statement Syntax

The syntax for the elseif statement in PHP is as follows:

<?php
 
if (condition)
{
    // do something
}
elseif (condition)
{
    // do something else
}
elseif (condition)
    ...
    ...
    ...
else
{
    // do the last thing
}
 
?>

What this allows us to do is add as many other checks as we like to a particular piece of code. We are no longer limited to the either-or method of branching which we get when we use the PHP if else statement.

PHP Elseif Statement Example

The PHP elseif statement is particularly helpful when dealing with a number of conditions to be checked. Have a look at the example below:

<?php
 
$size = 'large';
 
if ($size == 'small')
{
    echo 'Small';
}
elseif ($size == 'medium')
{
    echo 'Medium';
}
else
{
    echo 'Large';
}
 
?>

The result of this code would be:

Large

As we can see, we are able to add as many of these statements as required to achieve our solution. As soon as the interpreter finds a condition that is true, it will execute whatever code which is in the block for that condition.

If no conditions are true then it will evaluate the final else. Note though, that this final else does not have to be a part of our if-elseif block, for example, in a situation where we do not want to perform an action when no conditional match is met.

PHP Elseif Statement Tips

Remember that the elseif statement is a conditional statement like the if statement and must be checking for a condition. A block of these statements must always start with an if statement and may or may not end with an else statement.

We hope this PHP elseif statement tutorial has been helpful.

Link to this Page

Thank Tutorial Arena for This Tutorial.
Show your appreciation with a +1...