Get "PHP 8 in a Nuthshell" (Soon includes PHP 8.4)
Amit Merchant

Amit Merchant

A blog on PHP, JavaScript, and more

The difference between 'elseif' and 'else if' in PHP

PHP is funny sometimes. There are many things in PHP which behaves differently instead of the way you think might work. I recently stumbled upon one such thing while working on one of my projects.

There are basically following ways of writing two or more conditions in conditional statements. i.e using else if and elseif. We’ll discuss both of them here.

Using “elseif” in conditionals

We can write a conditional statement involving two or more conditions like below.

if ($condition1) {
    // ...
} elseif ($condition2) {
    // ...
} else {
    // ...
}

In the above statement, the elseif is one statement by itself. So, it will check the first condition $condition1, if that becomes false, it will then checks the second condition $condition2 and if it becomes true, PHP will excute the code in the block following the condition.

Using “else if” in conditionals

On the other hand, We can write a conditional statement involving two or more conditions using else if like below.

if ($condition1) {
    // ...
} else if ($condition2) {
    // ...
} else {
    // ...
}

You might think that the above example and the previous one using elseif behaves same but you’re mistaken in this case. In the above case, else if is interpreted as an if statement in the else of the first if. As you can see, the conditionals becomes nested in this case.

The code above is actually interpreted like below:

if ($condition1) {
    // ...
} else {
    if ($condition2) {
        // ...
    } else {
        // ...
    }
}

So basically, there’s not much of a difference in using else if versus elseif other than the latter is a “syntactic sugar”. However, if you’re following PHP Standard Recommendations, PSR-2 is actually recommeds using elseif instead of else if as a standard approach. So, it’s a rather good idea to use elseif in your code whenever possible.

Learn the fundamentals of PHP 8 (including 8.1, 8.2, and 8.3), the latest version of PHP, and how to use it today with my new book PHP 8 in a Nutshell. It's a no-fluff and easy-to-digest guide to the latest features and nitty-gritty details of PHP 8. So, if you're looking for a quick and easy way to PHP 8, this is the book for you.

Like this article?

Buy me a coffee

👋 Hi there! I'm Amit. I write articles about all things web development. You can become a sponsor on my blog to help me continue my writing journey and get your brand in front of thousands of eyes.

Comments?