Alternate If Statements In PHP

20th January 2008

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:

  1. if($something == $somethingelse){
  2. //do something
  3. }elseif($something == $anotherthing){
  4. //do another thing
  5. }else{
  6. // default action
  7. }

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.

  1. if($something == $somethingelse)
  2. // 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.

  1. if($something == $somethingelse):
  2. // do something
  3. elseif($something == $anotherthing):
  4. // do another thing
  5. else:
  6. // default action
  7. 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:

  1. $value = true;
  2. 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.

  1. $value = true;
  2. 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.