Bug #70857 [NEW]: Foreach with a reference is modifying the result of a ternary expression

From: Date: Wed, 04 Nov 2015 20:45:59 +0000
Subject: Bug #70857 [NEW]: Foreach with a reference is modifying the result of a ternary expression
Groups: php.bugs 
Request: Send a blank email to php-bugs+get-197030@lists.php.net to get a copy of this message
From: nairebis at gmail dot com Operating system: CentOS 6.7 PHP version: 5.6.15 Package: Variables related Bug Type: Bug Bug description:Foreach with a reference is modifying the result of a ternary expression Description: ------------ Consider this line, where $a is an array: foreach (1 ? $a : [] as &$x) { According to the PHP documentation on ternary expressions, "Note: Please note that the ternary operator is an expression, and that it doesn't evaluate to a variable, but to the result of an expression. This is important to know if you want to return a variable by reference. The statement return $var == 42 ? $a : $b; in a return-by-reference function will therefore not work and a warning is issued in later PHP versions." The result of the ternary expression should not be an lvalue, and thus the above shouldn't work. But it actually does allow this. Test script: --------------- $a = [1, 2, 3, 4]; foreach (1 ? $a : [] as &$x) { $x += 10; } print_r($a); Expected result: ---------------- Array ( [0] => 1 [1] => 2 [2] => 3 [3] => 4 ) Actual result: -------------- Array ( [0] => 11 [1] => 12 [2] => 13 [3] => 14 ) -- Edit bug report at https://bugs.php.net/bug.php?id=70857&edit=1 -- Try a snapshot (PHP 5.4): https://bugs.php.net/fix.php?id=70857&r=trysnapshot54 Try a snapshot (PHP 5.5): https://bugs.php.net/fix.php?id=70857&r=trysnapshot55 Try a snapshot (trunk): https://bugs.php.net/fix.php?id=70857&r=trysnapshottrunk Fixed in SVN: https://bugs.php.net/fix.php?id=70857&r=fixed Fixed in release: https://bugs.php.net/fix.php?id=70857&r=alreadyfixed Need backtrace: https://bugs.php.net/fix.php?id=70857&r=needtrace Need Reproduce Script: https://bugs.php.net/fix.php?id=70857&r=needscript Try newer version: https://bugs.php.net/fix.php?id=70857&r=oldversion Not developer issue: https://bugs.php.net/fix.php?id=70857&r=support Expected behavior: https://bugs.php.net/fix.php?id=70857&r=notwrong Not enough info: https://bugs.php.net/fix.php?id=70857&r=notenoughinfo Submitted twice: https://bugs.php.net/fix.php?id=70857&r=submittedtwice register_globals: https://bugs.php.net/fix.php?id=70857&r=globals PHP 4 support discontinued: https://bugs.php.net/fix.php?id=70857&r=php4 Daylight Savings: https://bugs.php.net/fix.php?id=70857&r=dst IIS Stability: https://bugs.php.net/fix.php?id=70857&r=isapi Install GNU Sed: https://bugs.php.net/fix.php?id=70857&r=gnused Floating point limitations: https://bugs.php.net/fix.php?id=70857&r=float No Zend Extensions: https://bugs.php.net/fix.php?id=70857&r=nozend MySQL Configuration Error: https://bugs.php.net/fix.php?id=70857&r=mysqlcfg

« previous php.bugs (#197030) next »