Evaluating If Else statements is very common in programming paradigm. But 'If Else' statements are long and they can be easily replaced by simply using Ternary operators. Here is a tutorial on the usage of ternary operators and their implementation in Php.
The ternary operator logic -
(condition) ? (true return value) : (false return value)
If condition is true execute the true block and if false then execute the false block
/* Simple usage */
$a = 2;
$a_is_greater_than_one = ($a > 1 ? true : false); // returns true
Advantages of implementing Ternary Logic :-
If/Else logic can be coded quicker
Short code
Code maintenace is easy
More Sample Usage
/* Basic usage */
$message = 'Hello '.($user->is_logged_in() ? $user->get('first_name') : 'Guest');
// If user is logged in then print Hello 'name' else print the name of user as guest
/* echo, inline */
echo 'On the basis of your score, you are ',($score > 90 ? 'a genius' : 'not a genius');
// If you're score is greater than 90 then you are a genius else you are not a genius
/* Next 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
0 Comment(s)