php.net |  support |  documentation |  report a bug |  advanced search |  search howto |  statistics |  random bug |  login
Bug #12566 Cascaded ternaries evaluate incorrectly
Submitted: 2001-08-04 15:33 UTC Modified: 2001-10-13 13:41 UTC
From: nick at macaw dot demon dot co dot uk Assigned:
Status: Not a bug Package: *Programming Data Structures
PHP Version: 4.0.6 OS: Linux
Private report: No CVE-ID: None
Welcome back! If you're the original bug submitter, here's where you can edit the bug or add additional notes.
If you forgot your password, you can retrieve your password here.
Password:
Status:
Package:
Bug Type:
Summary:
From: nick at macaw dot demon dot co dot uk
New email:
PHP Version: OS:

 

 [2001-08-04 15:33 UTC] nick at macaw dot demon dot co dot uk
The following emits 'two' rather than 'one' as one would expect.

$a = 1; $b = 2;

echo (($a == 1) ? 'one' : 
      ($b == 2) ? 'two' :
      'unknown');

Apologies if for PHP this unusual behaviour actually is as expected, but being counter-intuituve, and of course inconsistent from other languages with a ?: operator, this is an undesirable result.

In 'C', the following of course outputs 'one'

#include <stdio.h>

int main()
{
  int a = 1, b = 2;

  puts((a == 1) ? "one" : 
       (b == 2) ? "two" :
       "unknown");

  return 0;
}

Patches

Pull Requests

History

AllCommentsChangesGit/SVN commitsRelated reports
 [2001-08-04 17:04 UTC] jeroen@php.net
Confirmed in latest CVS:

---
echo TRUE ? 'one' : TRUE ? 'two' : 'unknown';
=> two
---
echo TRUE ? 'one' : FALSE ? 'two' : 'unknown';
=> two
---
This definitely is a bug, and IMO a serious one. A parse error would be acceptable IMO (then use ( and )), but this isn't.
 [2001-08-04 17:21 UTC] jeroen@php.net
adam@trachtenberg.com:
> It's not a "bug," but a "feature." :)
> 
> PHP has the inverse associativity of ?: compared to C (and every other
> language). This was originally a mistake, but now "it won't be changed,"
> due to historical reasons.
> 
> See some messages I had on php-dev back around the first week of January,
> 2001 on this topic. FWIW, I would like to change it.
> 
> -adam

So, you need to read it as:

echo (TRUE ? 'one' : TRUE) ? 'two' : 'unknown';,
and 
echo 'one' ? 'two' : 'unknown' is, correctly, 'two'


Maybe a fix for PHP 4.1 / PHP 5?


 [2001-10-13 13:41 UTC] sterling@php.net
nope.
 
PHP Copyright © 2001-2024 The PHP Group
All rights reserved.
Last updated: Sat Dec 21 16:01:28 2024 UTC