Saturday, 27 June 2015

PHP ? Operator (ternary operator)

/* most basic usage */
$var = 5;
$var_is_greater_than_two = ($var > 2 ? true : false); // returns true

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

/* a bit tougher */
$score = 10;
$age = 20;
echo 'Taking into account your age and score, you are: ',($age > 10 ? ($score < 80 ? 'behind' : 'above average') : ($score < 50 ? 'behind' : 'above average')); // returns 'You are behind'

0 comments:

Post a Comment