Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

If and else if in PHP, colon style

Tags:

php

One function of PHP that I like to use is the colon-style if statement (I don't know what it's actually called.)

<?php if(something):?>
    <html stuff>
<?php endif;?>

But I recently tried to do this with multiple cases:

<?php if(something):?>
    <html stuff>
<?php else if(something):?>
    <html stuff>
<?php endif;?>

And I get an error on the third line (the else if):

Unexpected T_IF

Is it possible to make an if-else if this way?

like image 793
Liftoff Avatar asked Apr 12 '15 18:04

Liftoff


People also ask

How we use if...else and ELSE IF statement in PHP?

if...else statement - executes some code if a condition is true and another code if that condition is false. if... elseif...else statement - executes different codes for more than two conditions. switch statement - selects one of many blocks of code to be executed.

Can I use else if in PHP?

In PHP, you can also write 'else if' (in two words) and the behavior would be identical to the one of 'elseif' (in a single word). The syntactic meaning is slightly different (if you're familiar with C, this is the same behavior) but the bottom line is that both would result in exactly the same behavior.

Is it else if or Elseif?

Yes, "elseif" and "else if" both are synonymous, alike in meaning and significance. You can mix "else if" with "elseif" together. For Example - We can use "else if" and "elseif" together.

What is nested if...else statement in PHP?

The nested if statement contains the if block inside another if block. The inner if statement executes only when specified condition in outer if statement is true.


1 Answers

I was able to get it to work.

In this very specific case, else if is not synonymous with elseif.

Substituting elseif for else if fixes the issue.

<?php if(something):?>
    <html stuff>
<?php elseif(something):?>
    <html stuff>
<?php endif;?>

From PHP.net:

Note: Note that elseif and else if will only be considered exactly the same when using curly brackets as in the above example. When using a colon to define your if/elseif conditions, you must not separate else if into two words, or PHP will fail with a parse error.

like image 183
Liftoff Avatar answered Sep 27 '22 18:09

Liftoff