PHP

PHP (or Perl) one line if/then/else statements

August 8th, 2009

If you're toggling something between two states in PHP or Perl it's often handy to use an if/then/else one liner.

In pseudocode this goes like this:

<if this evaluates to TRUE> then <parse this> else <parse this>

All you need to do is replace the "then" with a question mark and the "else" with a colon:

<if this evaluates to TRUE> ? <parse this> : <parse this>

For example:

print  $trueOrFalse ? "you're telling the truth" : "you're lying";

Ignore the print command, it's not part of the if/then/else statement, it's just here to do something with the outcome of that statement.

The expression immediately to the left of the question mark is evaluated. The expression between the question mark and the colon is parsed if the expression evaluates to TRUE, otherwise the expression immediately to the right of the colon is parsed. So in the above example, either "you're telling the truth" or "you're lying" is printed, depending on whether $trueOrFalse is ... you guessed it ... TRUE or FALSE.

But perhaps a more common situation is toggling the value assigned to a variable. For example, toggling between TRUE and FALSE:

$trueOrFalse = $trueOrFalse ? FALSE : TRUE;

Here's a practical example of the use of if/then/else one liners. There's two in this chunk of PHP. The scroll box list below the code is the kind of thing this PHP produces.

<div style="overflow:auto; height:100px; width:300px; border:3px groove #DDD; padding:0">
<?php
    $alternateLine = FALSE;
    while($presidentsArray) {
        print "<div style=\"background-color:";
        print $alternateLine ? "#F5F8F9" : "white";
        print "; padding-bottom: 1px\"> &nbsp; &nbsp; <a href=\"someURL\" title=\"This link goes nowhere\">" .
          $presidentsArray['name'] . "</a></div>";
        $alternateLine = $alternateLine ? FALSE : TRUE;
    }
?>
</div>

Leave a comment

 

^ back to top ^

Page 1 of 11