PHP Shorthand If Else Using Ternary Operator
PHP How ToAlmost all the programs require evaluating conditions using if/else and switch/case statements. If-Else statements are easy to code and global to all languages. However, they can be too long. The ternary operator (?:) can replace a single if/else clause.
Ternary Operators - ?:
Ternary operator logic is the process of using "(condition) ? (true return value) : (false return value)" statements to shorten your if-else structures.
/* basic usage */
$var = 7;
$var_is_greater_than_two = ($var > 2 ? true : false); // returns true
Advantages of Ternary Logic
There are many advantages of using this type of logic:
- Makes coding simple if-else logic quicker
- You can do your if-else logic inline with output
- Makes code shorter
- Makes maintaining code quicker, easier
Tips for Using Ternary Operators
- Don't go more levels deep than what you feel comfortable with maintaining.
- If you work in a team setting, make sure other programmers understand the code.
- Avoid stacking ternary operators.
- If you are not 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.
Examples
Example 1: Message according to user's login status.
/* user basic usage */
$message = 'Hello '.($user->is_logged_in() ? $user->get('first_name') : 'Guest');
Example 2
/* echo, inline */
echo 'Based on your score, you are a ',($score > 10 ? 'genius' : 'nobody');