Difference between “elseif” and “else if” in PHP

Me, a self taught, self declared web developer; working with php for more than 3 years now; more often than not forgets this very simple yet confusing flow statement. Should I use ‘elseif’ ? Or is it ‘else if’ ? Sounds familiar , huh ?

So, I decided to write this blog as part of the journey to remind myself again and to help any novice out there searching for answers! It’s pretty simple though. You use ‘else if’ or ‘elseif’ if you use the standard curly braces in flow statement. Consider the following example:

if( something == something ){

} elseif ( nothing != nothing ) {

}else if ( anything == anything ){

} else {

}

Notice that I used both ‘elseif’ and ‘else if’ there. And that’s perfectly valid as long as you’re using curly braces for the block. Now let’s see what happens when we use colon instead of the curly braces.

if( something == something) :

elseif ( nothing != nothing ) :

else if ( anything == anything ) :

else :

endif;

When you run this code, what do you see ? That’s right. A parse error. PHP will consider ‘elseif’ and ‘else if’ to be equal if and only if they are used inside curly braces. If you want to use colon, USE ‘elseif’ .

if( something == something) :

elseif ( nothing != nothing ) :

elseif ( anything == anything ) :

else :

endif;

That’s it!

Leave a Reply

Close Menu