Question Detail

What exactly is the ternary operator works and how it differ then an

6 years ago Views 1168 Visit Post Reply

I am confused in, we have If else and also have ternary operator.
Why exactly is the ternary operator works and how it differs by our If else? Whan we use ternary Operator?


Thread Reply

Anonymous

- 6 years ago

A Ternary is not a good solution for what you want. It will not be readable in your code, and there are much better solutions available.

Why not use an array lookup "map" or "dictionary", like so:

$vocations = array(
    1 => "Sorcerer",
    2 => "Druid",
    3 => "Paladin",
    ...
);

echo $vocations[$result->vocation];

A ternary for this application would end up looking like this:

echo($result->group_id == 1 ? "Player" : ($result->group_id == 2 ? "Gamemaster" : ($result->group_id == 3 ? "God" : "unknown")));

Why is this bad? Because - as a single long line, you would get no valid debugging information if something were to go wrong here, the length makes it difficult to read, plus the nesting of the multiple ternaries just feels odd.

A Standard Ternary is simple, easy to read, and would look like this:

$value = ($condition) ? 'Truthy Value' : 'Falsey Value';

or

echo ($some_condition) ? 'The condition is true!' : 'The condition is false.';

A ternary is really just a convenient / shorter way to write a simple if else statement. The above sample ternary is the same as:

if ($some_condition) {
    echo 'The condition is true!';
} else {
    echo 'The condition is false!';
}

However, a ternary for a complex logic quickly becomes unreadable, and is no longer worth the brevity.

echo($result->group_id == 1 ? "Player" : ($result->group_id == 2 ? "Gamemaster" : ($result->group_id == 3 ? "God" : "unknown")));

Even with some attentive formatting to spread it over multiple lines, it's not very clear:

echo($result->group_id == 1 
    ? "Player" 
    : ($result->group_id == 2 
        ? "Gamemaster" 
        : ($result->group_id == 3 
            ? "God" 
            : "unknown")));
 

Hemant Sharma

- 6 years ago

What Does Ternary Logic Look Like?

 

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

What Are The Advantages of Ternary Logic?

There are some valuable advantages to using this type of logic:

  • Makes coding simple if/else logic quicker
  • You can do your if/else logic inline with output instead of breaking your output building for if/else statements
  • Makes code shorter
  • Makes maintaining code quicker, easier
  • Job security?

Hemant Sharma

- 6 years ago

What Does Ternary Logic Look Like?

 

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

What Are The Advantages of Ternary Logic?

There are some valuable advantages to using this type of logic:

  • Makes coding simple if/else logic quicker
  • You can do your if/else logic inline with output instead of breaking your output building for if/else statements
  • Makes code shorter
  • Makes maintaining code quicker, easier
  • Job security?

Hemant Sharma

- 6 years ago

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 behavior 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."

Hemant Sharma

- 6 years ago

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 behavior 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."

Hemant Sharma

- 6 years ago

Here are a couple more uses of ternary operators, ranging from simple to advanced:

/* 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'); //harsh!
/* 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'
/* "thankfully-you-don't-need-to-maintain-this" level */
 $days = ($month == 2 ? ($year % 4 ? 28 : ($year % 100 ? 29 : ($year %400 ? 28 : 29))) : (($m

Hemant Sharma

- 6 years ago

Here are a couple more uses of ternary operators, ranging from simple to advanced:

/* 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'); //harsh!
/* 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'
/* "thankfully-you-don't-need-to-maintain-this" level */
 $days = ($month == 2 ? ($year % 4 ? 28 : ($year % 100 ? 29 : ($year %400 ? 28 : 29))) : (($m