Viewed   87 times

I use ternary operators alot but I can't seem to stack multiple ternary operator inside each other.

I am aware that stacking multiple ternary operator would make the code less readable but in some case I would like to do it.

This is what I've tried so far :

$foo = 1;
$bar = ( $foo == 1 ) ? "1" : ( $foo == 2 ) ? "2" : "other";
echo $bar; // display 2 instead of 1

What is the correct syntax ?

 Answers

2

Those parenthesis are what I think is getting you.

Try

$foo = 1;
$bar = ($foo == 1) ? "1" : (($foo == 2)  ? "2" : "other");
echo $bar;
Saturday, August 13, 2022
1

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")));
Thursday, November 24, 2022
2

The

(condition) ? /* value to return if condition is true */ 
            : /* value to return if condition is false */ ;

syntax is not a "shorthand if" operator (the ? is called the conditional operator) because you cannot execute code in the same manner as if you did:

if (condition) {
    /* condition is true, do something like echo */
}
else {
    /* condition is false, do something else */
}

In your example, you are executing the echo statement when the $address is not empty. You can't do this the same way with the conditional operator. What you can do however, is echo the result of the conditional operator:

echo empty($address['street2']) ? "Street2 is empty!" : $address['street2'];

and this will display "Street is empty!" if it is empty, otherwise it will display the street2 address.

Sunday, November 13, 2022
 
2

You need to bracket the ternary conditionals:

<?php

for ($a=0; $a < 7; $a++) {
  echo (
    $a == 1 ? 'one' :
    ($a == 2 ? 'two' :
    ($a == 3 ? 'three' :
    ($a == 5 ? 'four' : 'other'))));
    echo "n";
    // prints 'four'
}
exit;
?>

returns:

other
one
two
three
other
four
other

as you'd expect.

See the note at the bottom of "Ternary operators" at PHP Ternary operator help.

The expressions are being evaluated left to right. So you are actually getting:

  echo (
    ((($a == 1 ? 'one' : $a == 2)
     ? 'two' : $a == 3) ? 'three' :
    $a == 5) ? 'four' : 'other');

So for $a=2, you get:

  echo (
    ((($a==2) ? 'two' : $a == 3) ? 'three' :
    $a == 5) ? 'four' : 'other');

and then

  echo (
    ((true ? 'two' : $a == 3) ? 'three' :
    $a == 5) ? 'four' : 'other');

and then

  echo (
    ('two' ? 'three' : $a == 5) ? 'four' : 'other');

and then

  echo (
    'three' ? 'four' : 'other');

and so echo 'four'.

Remember that PHP is dynamically typed and treats any non-zero non-null values as TRUE.

Monday, December 12, 2022
4

Expression.IfThenElse is an if (...) ... else ...; construct, not the ternary operator.

The ternary operator is Expression.Condition

Wednesday, August 17, 2022
 
joshue
 
Only authorized users can answer the search term. Please sign in first, or register a free account.
Not the answer you're looking for? Browse other questions tagged :