+ 3

Ternary operator

consider code bellow: $var =true? '1' : false? '2': '3' Why the Value of $var is '2' and we have the true value '1'? second: $var =true? '1' : false? '2': '3' $var =true? '1' : true? '2': '3' $var =false? '1' : false? '2': '3' $var =false? '1' : true? '2': '3' in all cases the value of $var is '2' Please let me know understand the main idea behind ternary in php. Regard

16th Oct 2019, 5:52 AM
Moh Waleed Sharifi
3 Antworten
+ 9
I think order precedence comes into play and '1' replaces true which returns '2'. Since false will not be evaluated. Looks like a language bug but i doubt its. #HappyCoding
16th Oct 2019, 10:11 AM
BlackRose Mike
BlackRose Mike - avatar
+ 2
it may sound crazy, but ternary in php is left-associative here's the proof https://www.php.net/manual/en/language.operators.precedence.php so true?'1':false?'2':'3' will become '1'?'2':'3' resulting '2' true?'1':false will get executed, then the the result is used for the next operation
16th Oct 2019, 6:25 AM
Taste
Taste - avatar