Ternary operator associativity
| From: | Ryan Jentzsch | Date: | Thu, 30 Apr 2020 11:11:08 +0000 |
| Subject: | Ternary operator associativity | ||
| Groups: | php.internals | ||
| Request: | Send a blank email to internals+get-109943@lists.php.net to get a copy of this message | ||
Is there a possibility this can be fixed in version 8? From
http://phpsadness.com/sad/30 listed as an outright bug (I
don't have
the C skills to fix this. I am just raising this as an issue that has
been a criticism of PHP for many years now with a new major version
upcoming that could allow for a b/c of this significance to improve
the language):
The ternary operator is left-associative and therefore behaves
entirely incorrectly:
$ cat ternary.php
<?php
echo (FALSE ? "a" : FALSE ? "b" : "c")."\n";
echo (FALSE ? "a" : TRUE ? "b" : "c")."\n";
echo (TRUE ? "a" : FALSE ? "b" : "c")."\n";
echo (TRUE ? "a" : TRUE ? "b" : "c")."\n";
?>
$ php ternary.php
c
b
b
b
In any other language with a ternary operator, you can stack them and
build an if-elseif-elseif-else expression:
$ cat ternary.pl
#!/usr/bin/perl -w
use strict;
print +(0 ? "a" : 0 ? "b" : "c")."\n";
print +(0 ? "a" : 1 ? "b" : "c")."\n";
print +(1 ? "a" : 0 ? "b" : "c")."\n";
print +(1 ? "a" : 1 ? "b" : "c")."\n";
$ perl ternary.pl
c
b
a
a