|
Posted by Andy Hassall on 05/22/05 15:57
On 21 May 2005 22:04:33 -0700, "Chung Leong <chernyshevsky@hotmail.com>"
<chernyshevsky@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 / <andy@andyh.co.uk> / <http://www.andyh.co.uk>
<http://www.andyhsoftware.co.uk/space> Space: disk usage analysis tool
Navigation:
[Reply to this message]
|