Tuesday, April 28, 2009

Ternary Operator (Short IF Statements) in PHP

This is a cool little 'trick' if you want a quick IF statement in PHP.  You'd use the Ternary Operator which would evaluate similar to the IF operator.

Syntax is like this:

// Example usage for: Ternary Operator
$action = ("john" != "frank") ? 'john isnt frank' 'john is frank';


So in this case, the output 'john isnt frank' would be saved to $action.

The first portion of the before the ? is what is being evaluated.  So we check if the string "john" is not equal to "frank".

Between the ? and the : is what to do if we returned TRUE.

Between the : and the ; is what to do if we returned FALSE.

Since I have $action = at the beginning, the output is saved to that variable.

For more info on this, see the PHP documentation: http://uk2.php.net/operators.comparison (you'll need to scroll down a little)

No comments: