By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
454,409 Members | 1,604 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 454,409 IT Pros & Developers. It's quick & easy.

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

P: n/a
Why does the following script output 3? Can anyone explain that?

<?php
echo true? 2: false? 3: 4 ;
?>

Thanks,
-Marcin
Jul 17 '05 #1
Share this Question
Share on Google+
4 Replies


P: n/a
On Sat, 21 May 2005 09:24:55 +0200, Marcin wrote:
Why does the following script output 3? Can anyone explain that?
echo true? 2: false? 3: 4 ;


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 - http://getffox.com/
Thunderbird E-mail and Newsgroups - http://gettbird.com/
Jul 17 '05 #2

P: n/a
Interesting. In C, you would get 2,

Jul 17 '05 #3

P: n/a
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).

Chung Leong <ch***********@hotmail.com> wrote:
Interesting. In C, you would get 2,


Jul 17 '05 #4

P: n/a
On 21 May 2005 22:04:33 -0700, "Chung Leong <ch***********@hotmail.com>"
<ch***********@hotmail.com> wrote:
Interesting. In C, you would get 2,


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

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
2

andyh@server:~/tmp/ternary$ cat ternary.pl
#!/usr/bin/perl
print 1 ? 2 : 0 ? 3 : 4;
print "\n";
andyh@server:~/tmp/ternary$ ./ternary.pl
2

andyh@server:~/tmp/ternary$ cat ternary.php
<?php
echo true ? 2 : false ? 3 : 4;
echo "\n";
?>
andyh@server:~/tmp/ternary$ php -q ternary.php
3
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.

--
Andy Hassall / <an**@andyh.co.uk> / <http://www.andyh.co.uk>
<http://www.andyhsoftware.co.uk/space> Space: disk usage analysis tool
Jul 17 '05 #5

This discussion thread is closed

Replies have been disabled for this discussion.