PHP Ternary Operator
Learn about PHP Ternary Operator with logical examples:
What Are The Advantages of Ternary Logic?
There are some valuable advantages to using this type of logic:
- Makes coding simple if/else logic quicker
- You can do your if/else logic inline with output instead of breaking your output building for if/else statements
- Makes code shorter
- Makes maintaining code quicker, easier
- Job security?
Tips for Using Ternary Operators
Here are a few tips for when using “?:” logic:
- Don’t go more levels deep than what you feel comfortable with maintaining.
- If you work in a team setting, make sure the other programmers understand the code.
- PHP.net recommends avoiding stacking ternary operators. “Is [sic] is recommended that you avoid “stacking” ternary expressions. PHP’s behaviour when using more than one ternary operator within a single statement is non-obvious.”
- If you aren’t experienced with using ternary operators, write your code using if/else first, then translate the code into ?’s and :’s.
- Use enough parenthesis to keep your code organized, but not so many that you create “code soup.”
More Sample Usage
Here are a couple more uses of ternary operators, ranging from simple to advanced:
/* another basic usage */ $message = 'Hello '.($user->is_logged_in() ? $user->get('first_name') : 'Guest');
/* shorthand usage */ $message = 'Hello '.($user->get('first_name') ?: 'Guest');
/* echo, inline */ echo 'Based on your score, you are a ',($score > 10 ? 'genius' : 'nobody'); //harsh!