14th December 2015
In
PHP, Web Development
Ternary Operator (:?)
The ternary operator is a shorthand for if/else.
Why bother with the ternary operator?
Wherever possible it makes sense to optimize your code. In so doing you reduce the load on the server and write less code (never a bad thing!). By optimizing your scripts as much as possible will also make your project easier to maintain.
So how does the Ternary operator work?
$scoreA = 10;
$scoreB = 20;
/*Ternary operators are if/else statements in shorthand*/
/* If condition is true then assign $scoreA to result otheriwise $scoreB */
$result = ($scoreA > $scoreB) ? $scoreA : $scoreB;
What’s happening?
The best way to demonstrate this is to write this in an if/else:
$scoreA = 10;
$scoreB = 20;
if($scoreA > $scoreB)
{
$result = $scoreA ;
}
else
{
$result = $scoreB;
}
So the important outcome from this is that the ternary operator will always return something – true or false, one result or another.
Another example
$loggedIn = ($passwordEntered == $passwordRetrieved) ? $passwordEntered : $passwordRetrieved;
if($loggedIn)
{
//Proceed with the rest of the application
}
else
{
//Exit the application
exit();
}
Use sparingly
Don’t go nuts with these – use ternary operators on specific elements that do not need nesting.