|
php.net | support | documentation | report a bug | advanced search | search howto | statistics | random bug | login |
[2004-11-18 15:40 UTC] Arne dot Heizmann at csr dot com
Description:
------------
The ternary conditional operator (?:) goes wrong when nested two levels deep.
When adding parentheses, the bug disappears, even when the parentheses are redundant and shouldn't make any difference.
Reproduce code:
---------------
echo true ? "Yes" :
false ? "No" : "No2";
Expected result:
----------------
"Yes"
Actual result:
--------------
"No"
PatchesPull RequestsHistoryAllCommentsChangesGit/SVN commits
|
|||||||||||||||||||||||||||||||||||||
Copyright © 2001-2026 The PHP GroupAll rights reserved. |
Last updated: Wed Oct 07 23:00:01 2026 UTC |
I understand now that the test case outputs "No" because it interprets the code as: echo (true ? "Yes" : false) ? "No" : "No2"; but clearly this is not useful; I think the precedence of the operator should be changed so that programmers won't have to insert extra parentheses to disambiguate the construct.Ah... thanks for your comment, tony2001@php.net. I think it should work the other way than it does because it is more useful. Situations in which you want to use the result of a conditional ?: operation as the condition in other ?: operation are extremely rare. It is much more likely that you want to go through a set of cases, such as: $result = $var == 1 ? 'Result 1' : $var == 2 ? 'Result 2' : $var == 3 ? 'Result 3' : $var == 4 ? 'Result 4' : ''; According to the way the operator currently works, this requires a heck of a lot of parentheses: $result = $var == 1 ? 'Result 1' : ($var == 2 ? 'Result 2' : ($var == 3 ? 'Result 3' : ($var == 4 ? 'Result 4' : ''))); which I think is pretty ugly.