Alternate If Statements In PHP

If you have programmed in PHP for any amount of time then you will be farmiliar with the if statement. The syntax is as follows:

if($something == $somethingelse){
  //do something
}elseif($something == $anotherthing){
  //do another thing
}else{
  // default action
}

The PHP engine also allows you to do what I call "lazy programming" where you don't need the curly braces. Only the line underneath the if statement is run if the if clause if met.

if($something == $somethingelse)
  // do something

The issue here is that when this is put into the rest of the program the code becomes almost unreadable and therefore unmaintainable. The curly brases make it much easier to see what a program is doing. For readability and maintenance, many developers consider it bad style not to include them.

There is also an alternate mechanism which uses a colon (:) in the place of the trailing curly brace and uses endif at the close of the statement. Here is an example.

if($something == $somethingelse): 
  // do something
elseif($something == $anotherthing):
  // do another thing
else:
  // default action
endif;

Finally, you can use the ternary or "?:" operator. This has the following syntax:

$item = ($something==1) ? 'yes' : 'no';

This is fine when you are doing very simple statements like this, but you can find it producing odd results or just being completely undreadable when you start to nest them. The ternary operator is evaluated from left to right so doing this:

$value = true;
echo ($value==true)?'true':($value==false)?'t':'false';

Will produce the result t, which is wrong! To solve this you need to separate the different parts with parenthesis. Here is the correct version of the above example.

$value = true;
echo ($value==true)?'true':(($value==false)?'t':'false');

Any more than two levels and this type of statement can be very confusing so I suggest that you only use this when you know for certain that you are looking for one thing or the other.

Add new comment

The content of this field is kept private and will not be shown publicly.
CAPTCHA
3 + 0 =
Solve this simple math problem and enter the result. E.g. for 1+3, enter 4.
This question is for testing whether or not you are a human visitor and to prevent automated spam submissions.