PHP Ternary Operator - Shortcut to IF ELSE
I consider this chunk to be one you should use with caution.
Above all else, write your code with readability in mind. Don’t get caught in the mentality of “less lines, better code”, as this will ensure any future changes give you or someone else major headaches.
That said, if you have a simple IF ELSE statement then it is possible to use the Ternary Operator syntax to shorten this down to 1 line. Consider the following:
if ($varA == $varB)Now this is no doubt fairly common in your applications - a simple comparison determining the value of a variable. This can feasibly be rewritten for one line and still be easily understandable:
{
$valid = true;
}
else
{
$valid = false;
}
$valid = ($varA == $varB ? true : false);Even someone who does not know about the Ternary Operator would be able to understand this without too much trouble, and will hopefully appreciate the simplicity of the statement. If you were to abuse the Ternary Operator by using it in complex or nested situations, you may well frustrate yourself and others who have to decipher its meaning.
So in conclusion, use the Ternary Operator only for simple comparisons.
