Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

unusual ternary operation

I was asked to perform this operation of ternary operator use:

$test='one';

echo $test == 'one' ? 'one' :  $test == 'two' ? 'two' : 'three';

Which prints two (checked using php).

I am still not sure about the logic for this. Please, can anybody tell me the logic for this.

like image 308
nik Avatar asked Apr 17 '10 14:04

nik


People also ask

What are examples of ternary operator?

Example: C Ternary Operator Here, age >= 18 - test condition that checks if input value is greater or equal to 18. printf("You can vote") - expression1 that is executed if condition is true. printf("You cannot vote") - expression2 that is executed if condition is false.

Is ternary operator bad practice?

Except in very simple cases, you should discourage the use of nested ternary operators. It makes the code harder to read because, indirectly, your eyes scan the code vertically. When you use a nested ternary operator, you have to look more carefully than when you have a conventional operator.

Which operations are known as ternary operator?

The conditional (ternary) operator is the only JavaScript operator that takes three operands: a condition followed by a question mark ( ? ), then an expression to execute if the condition is truthy followed by a colon ( : ), and finally the expression to execute if the condition is falsy.


1 Answers

Well, the ? and : have equal precedence, so PHP will parse left to right evaluating each bit in turn:

echo ($test == 'one' ? 'one' :  $test == 'two') ? 'two' : 'three';

First $test == 'one' returns true, so the first parens have value 'one'. Now the second ternary is evaluated like this:

'one' /*returned by first ternary*/ ? 'two' : 'three'

'one' is true (a non-empty string), so 'two' is the final result.

like image 174
Nicholas Wilson Avatar answered Oct 23 '22 18:10

Nicholas Wilson