Why should I care about PHP Shorthand If Notation or the Ternary Operator
Programming would be a bit useless without being able to evaluate conditions using if/end and switch statements. If/Else statements is obviously a great tool, but they aren’t optimal (or necessary) in all situations. And so I introduce you to … PHP Shorthand If Notation or the Ternary Operator.
Ternary operator takes the form “(condition) ? (true return value) : (false return value)” to shorten your if/else structures.
What Does It Look Like?
1 2 3
/* most basic usage */ $var = 5; $var_is_greater_than_two = ($var > 2 ? true : false); // returns true
Advantages of Ternary Logic?
Some advantages to using this type of logic:
- Makes coding simple if/else logic quicker.
- You can do your if/else logic in-line with output instead of breaking your output building for if/else statements.
- Makes code shorter.
- Makes maintaining code quicker, easier.
- Can be great for variable initialisation if used properly.
A few tips for when using “?:” logic:
- Don’t stack more than necessary, as this will make for hard to read code for those unfamiliar with it.
- If in a team setting, make sure the others understand the Ternary Operator and you’re usage of it with a decent comment if needed.
- If you aren’t experienced with this notation, write the code using if/else first, then convert it into ?’s and :’s.
- Use enough parenthesis to keep your code tidy, but not so many that you create code spaghetti!
More Usage Examples
A couple more uses, ranging from simple to advanced:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
/* most basic usage */ /* basic usage */ $message = 'Hello '.($user->isLoggedIn() ? $user->name : 'Guest'); /* echo, inline */ echo 'You have ',($score > 10 ? 'passed' : 'failed'); /* a bit tougher */ $score = 10; $age = 20; echo 'You have ',($age > 10 ? ($score < 80 ? 'failed' : 'Passed') : ($score < 50 ? 'failed' : 'passed')); // returns 'You are passed' /* An extreme example! */ $days = ($month == 2 ? ($year % 4 ? 28 : ($year % 100 ? 29 : ($year %400 ? 28 : 29))) : (($month - 1) % 7 % 2 ? 30 : 31)); //returns days in the given month
Only caveat in some languages may be precedence.
Read the manual!
To learn more about ternary operators view the PHP Manual’s section about Comparison Operators.