Bug #70857 [Opn->Csd]: Foreach with a reference is modifying the result of a ternary expression

From: Date: Tue, 31 Jan 2017 10:51:09 +0000
Subject: Bug #70857 [Opn->Csd]: Foreach with a reference is modifying the result of a ternary expression
References: 1  Groups: php.bugs 
Request: Send a blank email to php-bugs+get-207061@lists.php.net to get a copy of this message
Edit report at https://bugs.php.net/bug.php?id=70857&edit=1 ID: 70857 Updated by: nikic@php.net Reported by: nairebis at gmail dot com Summary: Foreach with a reference is modifying the result of a ternary expression -Status: Open +Status: Closed Type: Bug Package: Variables related Operating System: CentOS 6.7 PHP Version: 5.6.15 -Assigned To: +Assigned To: nikic Block user comment: N Private report: N New Comment: Closing as this is fixed in PHP 7 and PHP 5.6 is out of active support. Previous Comments: ------------------------------------------------------------------------ [2015-11-05 01:37:01] bwoebi@php.net This is fixed in PHP 7. Also it has inconsistent behavior thanks to copy on write: https://3v4l.org/jMjc8#v550 ------------------------------------------------------------------------ [2015-11-04 20:45:58] nairebis at gmail dot com 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 this bug report at https://bugs.php.net/bug.php?id=70857&edit=1

« previous php.bugs (#207061) next »