true?2:false?3:4 - is it a bug?

Do you have a question? Post it now! No Registration Necessary.  Now with pictures!

Threaded View

Why does the following script output 3? Can anyone explain that?

echo  true? 2:  false? 3: 4   ;


Re: true?2:false?3:4 - is it a bug?

On Sat, 21 May 2005 09:24:55 +0200, Marcin wrote:
Quoted text here. Click to load it

It is evaluated from left to right like so

  echo ((true ? 2 : false) ? 3 : 4);
  echo (2 ? 3 : 4);
  echo 3;

Firefox Web Browser - Rediscover the web - /
Thunderbird E-mail and Newsgroups - /

Re: true?2:false?3:4 - is it a bug?

Interesting. In C, you would get 2,

Re: true?2:false?3:4 - is it a bug?

In either language, you should use paranthesis, IMHO.  Not using them
requires that one be familiar with the order in which the particular
language evaluates expressions (which, incidently, is something most
people probably aren't going to be familiar with - you weren't.  I'm
not.  etc).

Quoted text here. Click to load it

Re: true?2:false?3:4 - is it a bug?

Quoted text here. Click to load it

 Indeed; PHP appears to have different results here to several other major

andyh@server:~/tmp/ternary$ cat ternary.c
#include <stdio.h>

#define TRUE 1
#define FALSE 0

int main()
    printf("%d\n", TRUE ? 2 : FALSE ? 3: 4);
    return 0;
andyh@server:~/tmp/ternary$ gcc -o ternary ternary.c
andyh@server:~/tmp/ternary$ ./ternary

andyh@server:~/tmp/ternary$ cat
print 1 ? 2 : 0 ? 3 : 4;
print "\n";
andyh@server:~/tmp/ternary$ ./

andyh@server:~/tmp/ternary$ cat ternary.php  
echo true ? 2 : false ? 3 : 4;
echo "\n";
andyh@server:~/tmp/ternary$ php -q ternary.php

 The issue is operator associativity; Perl (and C) implements the ternary
operator as right-associative, whereas PHP implements it as left-associative.

 This is documented in the Operators section in the PHP manual so it might be
hard to call it a bug, but it seems to be at least a design mistake to have
implemented it with the opposite associativity of the "original" languages.

< Space: disk usage analysis tool

Site Timeline