Official Killer Media Corporate Website (Click to View)

PHP Tip: Using the Ternary Operator

A ternary operator is an operator that takes three arguments in total. Two actual arguments and one result. The arguments and result can be of different types.
Many programming languages that use C-like syntax feature a ternary operator, (?:); unqualified, “ternary operator” usually refers to this. The (?:) operator is used as a shorthand replacement for the if-then-else conditional statement; the general form is condition ? op1 : op2. If condition is true, the statement evaluates as op1; otherwise, it evaluates as op2.

(Source.) Text in italics has been amended by Benjamin Eskew.

In PHP the above quote holds true for ternary operators and is very useful with many purposes and you should learn to use it religiously if you are not already. Here’s a few reasons why to use it so you know you won’t be wasting your time with this article:
Using the ternary operator will speed up the execution time of your code, reduce server memory/bandwidth usage/over-usage, and makes your code easier to read. On with the show…

You should be quite familiar with the following if-then-else statement:

if(expression){
     $var = “true value”;
}else{
     $var = “false value”;
}

There’s a much easier and more elegant way to go about this:

$var = (expression) ? “true value” : “false value”;

Example:

$var = true;
$return_value = ($var == true) ? “The variable is true.” : “The variable is false.”;
echo $return_value; // prints: The variable is true. to the browser window.

Leave a Reply

You must be logged in to post a comment.