How to Concatenate Multiple Ternary Operator in PHP

How to concatenate multiple ternary operator in PHP?

Those parenthesis are what I think is getting you.

Try

$foo = 1;
$bar = ($foo == 1) ? "1" : (($foo == 2) ? "2" : "other");
echo $bar;

Stacking Multiple Ternary Operators in PHP

Others have already suggested the right way of doing it but if you really want to use ternary operator you need to use parenthesis as:

$province = 7;
$Myprovince = (
($province == 6) ? "city-1" :
(($province == 7) ? "city-2" :
(($province == 8) ? "city-3" :
(($province == 30) ? "city-4" : "out of borders")))
);

Updated Link

Ternary operator concatenation

C, C++, Java, and Javascript will evaluate this as

1 == 1 ? 'green' : (1 < 0 ? 'red' : 'yellow')

due to the associativity of the ternary conditional operator being from right to left in all those languages. (This goes way back to before the if statement was even conceived).

But the PHP guys wanted to be different. In PHP, your expression is evaluated as

(1 == 1 ? 'green' : 1 < 0) ? 'red' : 'yellow'

This simplifies to 'green' ? 'red' : 'yellow' which in turn is 'red' as 'green' is truthy. If you want it the old-fashioned way then use the parentheses as above.

Ternary operator and string concatenation quirk?

$description = 'Paper: ' . ($paperType == 'bond' ? 'Bond' : 'Other');

Try adding parentheses so the string is concatenated to a string in the right order.

Multiple conditions in the ternary operator safe?

If the results you are returning from the ternary operator are only "true" and "false", then you don't even need the operator. You can just have:

$res = (($rule1 === true) && ($rule2 === false) && ($rule3 === true))

But, to answer your question, yes multiple conditions work perfectly well.

Multiple condition and expression with a ternary in php

If you want to account for another word instead of 'i.p. rating' in the title, you can have another ternary in the "else" part:

    id="ns_code_<?= ((stripos($title, 'i.p. rating') !== false) ? 'iprating' : ((stripos($title, 'whatever') !== false) ? 'whatever' : $title)) ?>"

At this point, I would suggest switching back to a standard condition block for a better readability.

Ternary operator with multiple conditions

This statement will always be true:

($var !== 1 || $var !== 2)

Because $var can never simultaneously be both values, it will always not be at least one of the two values. Which satisfies the || operator.

If you want to know whether $var is one of the two values:

($var === 1 || $var === 2)

If you want to know if $var is neither of the two values, you can negate the condition:

(!($var === 1 || $var === 2))

Or individually negate the operators in the condition and use && instead of || (since all conditions need to be met to prove the negative, instead of just one condition to prove the positive):

($var !== 1 && $var !== 2)

Depending on readability and personal preference.



Related Topics



Leave a reply



Submit