#30825 [Opn]: Ternary operator (?:) goes wrong
| From: | Arne dot Heizmann at csr dot com | Date: | Thu, 18 Nov 2004 15:09:09 +0000 |
| Subject: | #30825 [Opn]: Ternary operator (?:) goes wrong | ||
| References: | 1 | Groups: | php.bugs |
| Request: | Send a blank email to php-bugs+get-69216@lists.php.net to get a copy of this message | ||
ID: 30825
User updated by: Arne dot Heizmann at csr dot com
Reported By: Arne dot Heizmann at csr dot com
Status: Open
Bug Type: Unknown/Other Function
Operating System: Windows XP
PHP Version: 4.3.9
New Comment:
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.
Previous Comments:
------------------------------------------------------------------------
[2004-11-18 16:05:49] Arne dot Heizmann at csr dot com
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.
------------------------------------------------------------------------
[2004-11-18 16:03:32] tony2001@php.net
Could tell me how do you think it should work:
like this
echo (true ? "Yes" : false) ? "No" : "No2";
or like this
echo true ? "Yes" : (false ? "No" : "No2");
and why ?
------------------------------------------------------------------------
[2004-11-18 15:40:59] 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"
------------------------------------------------------------------------
--
Edit this bug report at http://bugs.php.net/?id=30825&edit=1