Using the Ternary Operator
The PHP language has many operators for evaluating one variable against another. These are normally mathematical symbols that test the relationship between one value and another. For example:
if( $a == $b )
will return true if the value of variable '$a' is equal to the value of variable '$b' (and thus execute the next line or braced coding). You should already be aware of many of the operators used in PHP and have an understanding of what they do.
The ternary operator is a coding structure that extends parenthesized operators and allows a single line to execute code for both the evaluated true and false returns. The most basic ternary structure is:-
($var_a [condition] $var_b) ? // do if true : // do if false ;
You could precede the above structure with an assignment such as
$a = ( 1 > 0 ) ? 'true' : 'false';
wherein $a would be assigned the value 'true' because 1 is larger than 0. You can also run a function call, prior or within the ternary. Take the following 'long winded' php snippet:-
$a = rand(0,10);
$b = rand(0,10);
if($a == $b)
{
echo 'Both the randomly generated numbers were the same - wahey!';
}
else
{
echo 'Try refreshing';
}
We could write this a number of ways:-
$a = rand(0,10);
$b = rand(0,10);
($a == $b) ? echo 'same' : echo 'different';
Note above that we type the pseudo-function echo twice, once for the true return and once for the false. As the called function is the same for both returns, we can reduce our code even more by moving the function call infront of the ternary...
echo ($a == $b) ? 'same' : 'different';
...or we can even pull the variable assignments within the conditional parenthesis and run the lot as one line.
echo (($a = rand(0,10)) == ($b = rand(0,10))) ? 'same' : 'different';
Things to remember so far:
The ternary structure always runs with the order (conditional) ? : ;
Executed code within the true return clause does NOT end with a semi-colon ;
Each executed clause of the ternary can only contain one function call or method.
The next part of this tutorial deals with scenarios where the ternary really can save time and help make your coding lean and efficient.
|