Web Statistics

if...elseif...else...

To be, or not to be...

if

One way to execute a section of code is to wrap the code in an if block.

$a = 10;
if ($a == 10) {
        print "The value is 10";
}

In the example above the code contained in the if block would be bypassed if the value of $a was not equal to 10. However, because the value of $a is equal to 10 the code in the if block is processed resulting in the process printing "The value is 10".

else

In the else block we are providing a secondary path for all instances that to not meet the if statement criteria and need to be handled differently.

$a = 9;
if ($a == 10) {
        print "The value is 10";
} else {
        print "The value is not 10";
}

Since the value of $a was not equal to 10 the if block was bypassed resulting in the process printing "The value is not 10".

elseif

By using the elseif block we are adding an additional exception that can bypass the if and the else blocks. The elseif can be used multiple times but a best practices rule is to use switch...

if your condition is more complicated than a simple compare and/or is in a tight loop.[php.net]
$a = 9;
if ($a == 10) {
        print "The value is 10";
} elseif ($a == 9) {
        print "The value is 9";
} else {
        print "The value is not 10";
}

Since the value of $a was not equal to 10 the if block was bypassed resulting in the process printing "The value is not 10".

Up Next

The big switch