Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to concatenate multiple ternary operator in PHP? [duplicate]

Tags:

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 ?

like image 661
Cybrix Avatar asked Jun 01 '11 14:06

Cybrix


People also ask

Can you stack ternary operators?

Nested Ternary operator: Ternary operator can be nested. A nested ternary operator can have many forms like : a ? b : c.

Is ternary operator faster than if in PHP?

So, why does the ternary operator become so slow under some circumstances? Why does it depend on the value stored in the tested variable? The answer is really simple: the ternary operator always copies the value whereas the if statement does not. Why?

How can I use ternary operator in PHP?

It is called a ternary operator because it takes three operands- a condition, a result statement for true, and a result statement for false. The syntax for the ternary operator is as follows. Syntax: (Condition) ? (Statement1) : (Statement2);

How many arguments does a ternary operator take?

The ternary operator take three arguments: The first is a comparison argument. The second is the result upon a true comparison. The third is the result upon a false comparison.


2 Answers

Those parenthesis are what I think is getting you.

Try

$foo = 1; $bar = ($foo == 1) ? "1" : (($foo == 2)  ? "2" : "other"); echo $bar; 
like image 113
Brandon Horsley Avatar answered Sep 18 '22 12:09

Brandon Horsley


The problem is that PHP, unlike all other languages, makes the conditional operator left associative. This breaks your code – which would be fine in other languages.

You need to use parentheses:

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

(Notice that I’ve removed the other parentheses from your code; but these were correct, just redundant.)

like image 41
Konrad Rudolph Avatar answered Sep 20 '22 12:09

Konrad Rudolph