The many different syntaxes of PHP’s if statement

The PHP language is blessed with many possible syntax structures for all sorts of language constructs. Some better than others but all have their place . Here we will be examining flexible usage of some of the styles available for use with if statements.

First, let’s look at the styles for the following statement in the standard c style:

$value = 1;
if ($value == 1) {
    print "if expression run";
} elseif ($value == 2) {
    print "elseif (1st) expression run";
} elseif ($value == 3) {
    print "elseif (2nd) expression run";
} else {
    print "else expression run";
}

(note: elseif has identical else if snytax in above and below examples)

In semi-colon syntax:

$value = 1;
if ($value == 1):
    print "if expression run";
elseif ($value == 2):
    print "elseif (1st) expression run";
elseif ($value == 3):
    print "elseif (2nd) expression run";
else:
    print "else expression run";
endif;

In switch statement format:

$value = 1;
switch (true) {
    case ($value == 1):
        print "if expression run";
        break;
    case ($value == 2):
        print "elseif (1st) expression run";
        break;
    case ($value == 3):
        print "elseif (2nd) expression run";
        break;
    default:
        print "else expression run";
};

The following are recursive language constructs.
In inline recursive format:

$value = 1;
($value == 1?
    (
        print "if expression run"
     ) :
    ($value == 2?
        (
            print "elseif (1st) expression run"
        ) :
        ($value == 3?
            (
                print "elseif (2nd) expression run"
            ):
            (
                print "else expression run"
            )
        )
    )
);

Using logical operators:

$value = 1;
$value == 1 and (print "if expression run")
or $value == 2 and (print "elseif expression run")
or $value == 3 and (print "elseif expression run")
or (print "else expression run");

 

Any other syntaxes missed?

Advertisements

Leave a Reply