PHP The else if clause

The else if clause

elseif, as its name suggests, is a combination of if and else. Like else, it extends an if statement to execute a different statement in case the original if expression evaluates to FALSE. However, unlike else, it will execute that alternative expression only if the elseif conditional expression evaluates to TRUE.

Syntax:

if(expr)
    statement
else if(expr)
    statement
else
    statement

For example, the following code would display a is greater than b, a equal to b or a is smaller than b:

Example:

<?php
    $a = 50;
    $b = 50;
    if ($a > $b) {
        echo "a is greater than b";
    } elseif ($a == $b) { //elseif also can be written as else if
        echo "a is equal to b";
    } else {
        echo "a is less than b";
    }
?>

Output:

The elseif statement is only executed if the preceding if expression and any preceding elseif expressions evaluated to FALSE, and the current elseif expression evaluated to TRUE.

Tutorialik.com
a is equal to b

There may be several elseifs within the same if statement. The only first elseif expression (if any) that evaluates to TRUE would be executed.
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.



Share This Page to Download:

Share to Download

Share This Page on:


Ask Question