Php challenge question | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

Php challenge question

In the following PHP challenge question: What is the value of $var? $var = true ? '1' : false ? '2' : '3'; 3 2 1 The accepted answer is 2, but when I run it in code playground: I get the message: Deprecated: Unparenthesized `a ? b : c ? d : e` is deprecated. Use either `(a ? b : c) ? d : e` or `a ? b : (c ? d : e)` in ./Playground/file0.php on line 2 2 https://code.sololearn.com/wL3VbQEw4FKh/?ref=app

29th Sep 2022, 9:28 AM
Edward Finkelstein
Edward Finkelstein - avatar
6 Answers
+ 2
Adding parentheses in the expression improves clarity. That quiz must've been posted in the days when PHP didin't care that much for expression clarity. $var = ( true ? '1' : false ) ? '2' : '3'; $var = ( '1' ) ? '2' : '3'; // non empty string are considered truthy $var = '2'; Hope I get that one right ...
29th Sep 2022, 12:47 PM
Ipang
+ 4
In every programming language other than PHP, the ternary operator is right-associative. This allows you to chain ternaries. x == 1 ? "one!" : x == 2 ? "two!" : "more than two!"; Since PHP was invented by a guy who didn't know what he was doing, PHP gets it wrong. That's the whole reason—it's an oversight. But, good on them for deprecating this unusual behaviour. You really shouldn't ever chain ternary expressions in practice anyway, it's really hard to read. :)
30th Sep 2022, 8:04 PM
Schindlabua
Schindlabua - avatar
+ 2
I just find it wierd why even old PHP parses it differently then C/C++. Anyway thanks Ipang
29th Sep 2022, 2:52 PM
Edward Finkelstein
Edward Finkelstein - avatar
+ 2
Anytime my friend 👌 I can only guess that C/C++ *probably* had short-circuited the evaluation, or has a different policy in short-circuiting; and therefore they came up with different result.
29th Sep 2022, 4:07 PM
Ipang
0
Also when I run on my home computer I get a similar message: PHP Fatal error: Unparenthesized `a ? b : c ? d : e` is not supported. Use either `(a ? b : c) ? d : e` or `a ? b : (c ? d : e)` in /Users/edwardfinkelstein/trash.php on line 2 Fatal error: Unparenthesized `a ? b : c ? d : e` is not supported. Use either `(a ? b : c) ? d : e` or `a ? b : (c ? d : e)` in /Users/edwardfinkelstein/trash.php on line 2
29th Sep 2022, 9:35 AM
Edward Finkelstein
Edward Finkelstein - avatar
0
Actually, in C programming language, the equivalent code: https://code.sololearn.com/caFpgk1SaA1i/?ref=app prints 1, not 2 Also in C++: https://code.sololearn.com/cGOwc3qij19J/?ref=app the result is 1, not 2. Since PHP is written in C, (and so is C++), if anything, I think the answer should be 1, not 2. Please explain. Any help is appreciated
29th Sep 2022, 9:40 AM
Edward Finkelstein
Edward Finkelstein - avatar