jcadima
5/20/2015 - 6:36 PM

PHP Ternary Operator

PHP Ternary Operator

<?php

/*  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!

/* "thankfully-you-don't-need-to-maintain-this" level */
 $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