04 Sep 2011

The ternary Operator

PHP, Webdeveloper 1 Comment

There is an operator in PHP that is very similar in functionality to the if statement called the ternary (?) conditional operator. It evaluates to check if the first subexpression is true, if it is it will return the value of the second subexpression, if the first subexpression is false it will return the value of the third subexpression.

Here is a example how is work:

$varname = (statement) ? truecode : falsecode;

Fairly obvious?

Statement – the statement to test. For example, could test a variable to see whether it matches some REGEX.
truecode – the code to execute if the statement returns true
falsecode – the code to execute if the statement returns false

$vartrue = 'True';
$varfalse = 'False';

$message = ($understood) ? $vartrue : $varfalse;

echo $message;

One Response to “The ternary Operator”

  1. diablo 3 trailer says:

    Excellent submit. I’m dealing with several these difficulties.

Leave a Reply