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

From: Date: Thu, 05 Nov 2015 01:37:03 +0000
Subject: Bug #70857 [Opn]: 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-197032@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: bwoebi@php.net Reported by: nairebis at gmail dot com Summary: Foreach with a reference is modifying the result of a ternary expression Status: Open Type: Bug Package: Variables related Operating System: CentOS 6.7 PHP Version: 5.6.15 Block user comment: N Private report: N New Comment: This is fixed in PHP 7. Also it has inconsistent behavior thanks to copy on write: https://3v4l.org/jMjc8#v550 Previous Comments: ------------------------------------------------------------------------ [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 (#197032) next »