Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP multiple ternary operator not working as expected

Why is this printing 2?

echo true ? 1 : true ? 2 : 3;

With my understanding, it should print 1.

Why is it not working as expected?

like image 732
Riz Avatar asked Jan 08 '13 11:01

Riz


People also ask

Can you do multiple things in a ternary operator?

The JavaScript ternary operator also works to do multiple operations in one statement. It's the same as writing multiple operations in an if else statement.

Is ternary operator faster than if in PHP?

The right answer is: it depends. Most of the time, they are about the same speed and you don't need to care. But if $context['test'] contains a large amount of data, snippet 2 is much faster than snippet 1.

Can we use nested ternary operator in PHP?

In PHP 7.4 using nested ternaries without explicit parentheses will throw a deprecation warning. In PHP 8.0 it will become a compile-time error instead.

How use ternary operator in if condition in PHP?

The syntax for the ternary operator is as follows. Syntax: (Condition) ? (Statement1) : (Statement2); Condition: It is the expression to be evaluated and returns a boolean value.


2 Answers

Because what you've written is the same as:

echo (true ? 1 : true) ? 2 : 3;

and as you know 1 is evaluated to true.

What you expect is:

echo (true) ? 1 : (true ? 2 : 3);

So always use braces to avoid such confusions.

As was already written, ternary expressions are left associative in PHP. This means that at first will be executed the first one from the left, then the second and so on.

like image 92
Leri Avatar answered Oct 14 '22 05:10

Leri


Separate second ternary clause with parentheses.

echo true ? 1 : (true ? 2 : 3);
like image 25
Lauris Avatar answered Oct 14 '22 05:10

Lauris