php.net |  support |  documentation |  report a bug |  advanced search |  search howto |  statistics |  random bug |  login
Doc Bug #10351 Parsing problem with nested ? : structures
Submitted: 2001-04-16 16:14 UTC Modified: 2004-07-26 15:25 UTC
From: dwilson at cae dot wisc dot edu Assigned:
Status: Closed Package: Documentation problem
PHP Version: 4.0.3pl1 OS: Sun OS 5.7
Private report: No CVE-ID: None
 [2001-04-16 16:14 UTC] dwilson at cae dot wisc dot edu
The following statement does not execute correctly:

             $departmeals = $dHour < 10.5 ? $dHour < 6.0 ? "3" : "2"  :
               $dHour < 18.0 ? "1" : "0";

No error message--it just returns the wrong result.  It does execute correctly if parentheses are added:

             $departmeals = $dHour < 10.5 ? ($dHour < 6.0 ? "3" : "2") :
               ($dHour < 18.0 ? "1" : "0");

The original is not ambiguous; it should parse and execute correctly.

Patches

Add a Patch

Pull Requests

Add a Pull Request

History

AllCommentsChangesGit/SVN commitsRelated reports
 [2002-04-27 15:19 UTC] jimw@php.net
it does execute correctly, given the relative precedence of the '<' and '?:' operators.
 [2002-04-29 10:34 UTC] dwilson at cae dot wisc dot edu
I checked, and < has a higher precedence than ?: as one
would expect.  For example, with $dHour = 5, this is
equivalent to:

$departmeals = 1 ? 1 ? "3" : "2" : 1 ? "1" : "0";

which should evaluate to "3" but evaluates to "1" instead.

The C language has no trouble with this construction:

sun-66% cat temp.c
#include <stdio.h>
main(){
    printf("%s\n",1 ? 1 ? "3" : "2" : 1 ? "1" : "0");
}
sun-66% cc temp.c
sun-66% a.out
3
 [2002-04-29 13:12 UTC] m dot ford at lmu dot ac dot uk
I think the key here is not precedence, but associativity.  The ?: operator is listed as being left-associative which, I think, means your simplified example will be evaluated like this:

(1 ? (1 ? "3" : "2") : 1) ? "1" : "0"

which will, indeed, result in 1!

A right-associative ?: would be grouped as you expected, like this:

1 ? (1 ? "3" : "2") : (1 ? "1" : "0")

-- ergo, in C ?: must be right-associative!!

(As a side-note, operator associativity is listed in the operator precedence table with no real explanation of what it means, or link to such explanation -- perhaps this should be made a documentation feature request?)
 [2004-07-26 15:25 UTC] vrana@php.net
This bug has been fixed in the documentation's XML sources. Since the
online and downloadable versions of the documentation need some time
to get updated, we would like to ask you to be a bit patient.

Thank you for the report, and for helping us make our documentation better.


 
PHP Copyright © 2001-2024 The PHP Group
All rights reserved.
Last updated: Fri Apr 26 18:01:31 2024 UTC