php.net |  support |  documentation |  report a bug |  advanced search |  search howto |  statistics |  random bug |  login
Doc Bug #36832 ternery operator parser improvement
Submitted: 2006-03-23 12:59 UTC Modified: 2006-09-07 18:57 UTC
Votes:1
Avg. Score:5.0 ± 0.0
Reproduced:1 of 1 (100.0%)
Same Version:0 (0.0%)
Same OS:1 (100.0%)
From: rdoggett at oz dot net Assigned:
Status: Closed Package: Documentation problem
PHP Version: 5.1.2 OS: any
Private report: No CVE-ID: None
 [2006-03-23 12:59 UTC] rdoggett at oz dot net
Description:
------------
The ternery operator causes grief because its parsing precedence is makedly different from other languages, as shown in the attached code.

One could reasonably expect the output to be "1 < 2", and indeed this is the case when translated to perl, c, or javascript.  It is difficult to believe that php's behavior could be an intentional language feature.

The problem can be solved by inserting nested parenthesis, so the parser's notion of operator precedence is implicated.

Although changing it to work more like other languages *could* break some existing php code, this seems very unlikely.  It could actually fix some unfound bugs.

Please, if you don't change the implementation, at least make the manual explain how the ternery operator's parsing precedence works. (with a big warning)



Reproduce code:
---------------
<?
$p = 1;
$out =  ($p < 2) ?  '< 2' :
        ($p > 4) ?  '> 4' :
                    '= $p';
echo "$p $out\n";
?>

Expected result:
----------------
1 < 2

Actual result:
--------------
1 > 4

Patches

Pull Requests

History

AllCommentsChangesGit/SVN commitsRelated reports
 [2006-09-07 18:57 UTC] colder@php.net
This is already stated in the documentation:

http://ch2.php.net/language.operators.comparison#language.operators.comparison.ternary
 
PHP Copyright © 2001-2025 The PHP Group
All rights reserved.
Last updated: Mon Aug 04 14:00:02 2025 UTC