PHP Decisions

PHP supports all the usual ways that programming languages provide for decision making. There are a few differences in the implementation though from the way some other languages implement them.

One construct available in PHP that some other languages don't have relates to the common compound if structure of IF, ELSE IF, ELSE where PHP provides a short version for that centre option with the elseif keyword being an abbreviation for else if which makes the code slightly more efficient because it let's PHP know that small amount more info about the structure so that the just in time compiler can look at the if statements in combination in working out how best to construct the executable code rather than having to treat each if statement separately.

if ($a == 5):
echo "a equals 5";
echo "...";
elseif ($a == 6):
echo "a equals 6";
echo "!!!";
echo "a is neither 5 nor 6";

Another alternative if structure that PHP provides that is not available in most other languages is to place a colon after the condition that is being tested in the if and elseif clauses and also after the keyword else. You can then include as many statements in each condition block without needing to use {} to wrap the block content. The if statement when you use the colon format is terminated by the keyword endif. Where you have multiple constructs nested inside one another the use of this alternative syntax can make the code easier to read since it isn't obvious wihc particular block a } is ending whereas endif makes it more obvious that it is the if statement that is being ended.

The way that PHP implements the switch statement is also slightly different from some other languages. To start with a switch statement also allows you to use the alternate syntax with a colon after the switch value instead of { and endswitch in place of the closing }.

switch ($i):
case 0:
echo "i equals 0";
case 1:
echo "i equals 1";
case 2:
echo "i equals 2";
default:echo "i is not equal to 0, 1 or 2";

Another thing to keep in mind with PHP switch statements is that the comparisons are loosely typed ones corresponding to == while some other languages such as JavaScript have their switch comparisons more tightly typed corresponding more closely to ===.


This article written by Stephen Chapman, Felgall Pty Ltd.

go to top

FaceBook Follow
Twitter Follow