PHP Shorthand If Else Using Ternary Operator

Almost 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:

  1. Makes coding simple if-else logic quicker
  2. You can do your if-else logic inline with output
  3. Makes code shorter
  4. Makes maintaining code quicker, easier

Tips for Using Ternary Operators

  1. Don't go more levels deep than what you feel comfortable with maintaining.
  2. If you work in a team setting, make sure other programmers understand the code.
  3. Avoid stacking ternary operators.
  4. If you are not experienced with using ternary operators, write your code using if-else first, then translate the code into ?'s and :'s.
  5. Use enough parenthesis to keep your code organized, but not so many.


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');