Learn PHP in 17 Days

Easy, non-nonsense guides to learning php. 47 lessons in total - click to get your copy of these fantastic guides.

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)
{
$valid = true;
}
else
{
$valid = false;
}
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 = ($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.

Are you a Developer, Designer or Copy Writer? Or Looking For One?

Click here to see 100s of jobs updated every day that you can complete to earn good money. Also find that programmer, designer or copy writer you have been looking for - advertise and get the best guy for your job - click here to find out more

Leave a Reply

Make $100,000/Month - Every Month!

It Works! We Make Our Customers Millionaires! Act now and get $600 bonus and a Free Money Making Website! - click to get started