An essential part of programming is evaluating conditions using if/else and switch/case statements. If / Else statements are easy to code and global to all languages. If / Else statements are great but they can be too long.
Ternary operator logic is the process of using "(condition) ? (true return value) : (false return value)" statements to shorten your if/else structures.
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:
Basic True / False Declaration
$is_admin = ($user['permissions'] == 'admin' ? true : false);
Conditional Welcome Message
echo 'Welcome '.($user['is_logged_in'] ? $user['first_name'] : 'Guest').'!';
Conditional Items Message
echo 'Your cart contains '.$num_items.' item'.($num_items != 1 ? 's' : '').'.';
Conditional Error Reporting Level
error_reporting($WEBSITE_IS_LIVE ? 0 : E_STRICT);
Nested PHP Shorthand
echo 'Your score is: '.
($score > 10 ? ($age > 10 ? 'Average' : 'Exceptional') : ($age > 10 ? 'Horrible' : 'Average') );
Leap Year Check
$is_leap_year = ((($year % 4) == 0) && ((($year % 100) != 0) || (($year %400) == 0)));
Conditional PHP Redirect
header('Location: '.($valid_login ? '/members/index.php' : 'login.php?errors=1')); exit();RITNIKOTKATA.COM