The ? Operator ( Elvis operator )

One way of avoiding the verbosity of if and else statements is to use the more compact ternary operator, ?, which is unusual in that it takes three operands rather than the typical two. We briefly came across this in Chapter 3 in the discussion about the difference between the print and echo statements as an example of an operator type that works well with print but not echo. The ? operator is passed an expression that it must evaluate, along with two statements to execute: one for when the expression evaluates to TRUE, the other for when it is FALSE. Example 4-26 shows code we might use for writing a warning about the fuel level of a car to its digital dashboard.
Example 4-26. Using the ? operator

echo $fuel <= 1 ? "Fill tank now" : "There's enough fuel";

In this statement, if there is one gallon or less of fuel (i.e., if $fuel is set to 1 or less), the string Fill tank now is returned to the preceding echo statement. Otherwise, the string There’s enough fuel is returned. You can also assign the value returned in a ? statement to a variable (see Example 4-27).

Example 4-27. Assigning a ? conditional result to a variable
$enough = $fuel <= 1 ? FALSE : TRUE;

Here $enough will be assigned the value TRUE only when there is more than a gallon of fuel; otherwise, it is assigned the value FALSE. If you find the ? operator confusing, you are free to stick to if statements, but you should be familiar with it because you’ll see it in other people’s code. It can be hard to read because it often mixes multiple occurrences of the same variable. For instance, code such as the following is quite popular:

$saved = $saved >= $new ? $saved : $new;

If you take it apart carefully, you can figure out what this code does:


$saved = // Set the value of $saved to...
$saved >= $new // Check $saved against $new
? // Yes, comparison is true ...
$saved // ... so assign the current value of $saved
: // No, comparison is false ...
$new; // ... so assign the value of $new

It’s a concise way to keep track of the largest value that you’ve seen as a program progresses. You save the largest value in $saved and compare it to $new each time you get a new value. Programmers familiar with the ? operator find it more convenient than if statements for such short comparisons. When not used for writing compact code, it is typically used to make some decision inline, such as when you are testing whether a variable is set before passing it to a function.


<< Prev Next >>

 303 total views,  3 views today