Using The Ternary Operator Instead of “If” Statements

The ternary operator is available in PHP and most other programming languages and usually it causes much confusion for novice programmers because of it’s unusual syntax. If you are going to write, modify or debug code, the ternary operator is invaluable because it allows you to simplify more complex conditionals into one line statements.

The basic syntax of the ternary operator is:

(condition) ? ‘true’ : ‘false';

What the statement above evaluates to is “If the condition is true, the first value (after the question mark) is returned. If the condition is false, the second value (after the colon) is returned. The trick to using the ternary operator is understanding that a value is returned by the expression and that the value must be handled as you would handle a valuereturned by a function or subroutine. A simple PHP example using the ternary operator is as follows :

<?Php
echo isDrinkingAge(24);

function isDrinkingAge($age)
{
return ($age > 21 ) ? “allowed to buy alcohol” : underage drinker;

}

In the example above, the output would be allowed to buy alcohol because the function isDrinkingAge() takes a number as an argument and uses the ternary operator to return one of two strings (“underage drinker” or “allowed to buy alcohol”) based on the condition ( $age < 21 ).

The code same isDrinkingAge() function could be written like this :


<?Php
echo isDrinkingAge(24);


function isDrinkingAge($age)
{
if ( $age > 21 ){
return "allowed to buy alcohol"
}else{
return "underage drinker";
}

While both examples are correct and proper, most experienced programmers will tend to use the ternary operator for code optimization reasons. This practice goes back to the early days of programming where a developer had to be careful and watch how many bytes they were using in their code because resources were limited. In todays modern computers, the conservation of bytes is not necessary, however, in terms of speed of execution the first example using the ternary operator will evaluate much faster than the second. While bytes are not necessary to conserve, if you are writing a web application in PHP that will be used simultaneously by thousands of web visitors (such as a forum or blog), the extra milliseconds of processing time can add up to a lot of CPU usage in the end.

About these ads

About this entry