|  support |  documentation |  report a bug |  advanced search |  search howto |  statistics |  random bug |  login
Bug #61915 incorrect associativity of ternary operator
Submitted: 2012-05-02 22:16 UTC Modified: 2012-05-02 22:38 UTC
From: iam4webwork at hotmail dot com Assigned:
Status: Not a bug Package: Scripting Engine problem
PHP Version: Irrelevant OS: Linux,Windows
Private report: No CVE-ID:
 [2012-05-02 22:16 UTC] iam4webwork at hotmail dot com
zend_language_parser.y on line 81 gives the '?:' operator left associativity when 
it should be right as in virtually every other language that has a ternary 

Test script:
$arg = "3";
$food = (  ($arg == '1') ? 'Banana' :
           ($arg == '2') ? 'Apple' :
           ($arg == '3') ? 'Toast' :
           ($arg == '4') ? 'Cantalope' :
           ($arg == '5') ? 'Swiss Cheese' : 'Fig Newton Cookie'
echo $food;

Expected result:
I expected to see 'Toast'. 

Actual result:
The actual result is 'Swiss Cheese'.


Add a Patch

Pull Requests

Add a Pull Request


AllCommentsChangesGit/SVN commitsRelated reports
 [2012-05-02 22:38 UTC]
Yes, this was an oversight when the language was defined and is documentedlike that on (see the last note). Unfortunately we can't fix this without breaking code, which depends on the current order, in a non-obvious way.
 [2012-05-02 22:38 UTC]
-Status: Open +Status: Not a bug
 [2012-11-12 14:47 UTC] sun at unleashedmind dot com
Recent major versions of PHP have introduced differences in behavior that are far worse than a correction of the ternary operator associativity would be.

IMHO, correcting this should be seriously considered for PHP 5.5 (or whatever is next ;)), since the current behavior is indeed very unexpected.

If PHP applications need to support older PHP major versions, then a version-agnostic ternary operator logic can be easily achieved through proper usage of parenthesis (which are required to achieve the expected ternary logic today already, right? -- which in turn, further undermines the compatibility argument?).

(Also, based on my experience with other developers who struggled with the current behavior, most of them simply gave up and changed their code to if/else or switch control structures in the first place.)
 [2016-12-16 14:37 UTC] tharkon at gmail dot com
I am a bit annoyed by the Note a bug status.
It is a bug, you just chose not to fix it.
PHP Copyright © 2001-2017 The PHP Group
All rights reserved.
Last updated: Sun Feb 26 21:01:35 2017 UTC