php.net |  support |  documentation |  report a bug |  advanced search |  search howto |  statistics |  random bug |  login
Bug #71214 foreach() with inline assignment breaks references
Submitted: 2015-12-24 19:49 UTC Modified: 2015-12-24 21:39 UTC
From: bugs dot php dot net at ss dot st dot tc Assigned:
Status: Not a bug Package: Scripting Engine problem
PHP Version: 7.0.1 OS: Linux, OSX
Private report: No CVE-ID: None
 [2015-12-24 19:49 UTC] bugs dot php dot net at ss dot st dot tc
Description:
------------
I believe both PHP 5.6 and 7 have bugs, but also they behave differently.
Tested on PHP 5.6.12, 5.6.16, 7.0.0, 7.0.1.


Test script:
---------------
<?php

# source array that we'll reference to later
$source = [ 'subarray' => ['item' => 'old value ---'] ];


# $ref1 is a reference to $source, assigned right in the foreach()
foreach ( $ref1 = $source as &$subarray ) {
	$subarray['item'] = 'NEW value';
	echo $subarray['item'], PHP_EOL;
	echo $ref1['subarray']['item'], PHP_EOL;
}
echo PHP_EOL;


# $ref2 is a "normal" reference to $source
$ref2 = $source;
foreach ( $ref2 as &$subarray ) {
	$subarray['item'] = 'NEW value';
	echo $subarray['item'], PHP_EOL;
	echo $ref2['subarray']['item'], PHP_EOL;
}
echo PHP_EOL;


########################################

# similar to $source array, but done using a function
function getSource() {
	return [ 'subarray' => ['item' => 'old value ---'] ];
}


# $ref3 is a reference to a result of getSource(), assigned right in the foreach()
foreach ( $ref3 = getSource() as &$subarray ) {
	$subarray['item'] = 'NEW value';
	echo $subarray['item'], PHP_EOL;
	echo $ref3['subarray']['item'], PHP_EOL;
}
echo PHP_EOL;


# $ref4 is a "normal" reference to a result of getSource()
$ref4 = getSource();
foreach ( $ref4 as &$subarray ) {
	$subarray['item'] = 'NEW value';
	echo $subarray['item'], PHP_EOL;
	echo $ref3['subarray']['item'], PHP_EOL;
}


Expected result:
----------------
both PHP 5 and 7:

NEW value
NEW value

NEW value
NEW value

NEW value
NEW value

NEW value
NEW value

Actual result:
--------------
PHP 7: 

NEW value
old value ---

NEW value
NEW value

NEW value
old value ---

NEW value
old value ---


PHP 5:

NEW value
old value ---

NEW value
NEW value

NEW value
NEW value

NEW value
NEW value

Patches

Pull Requests

History

AllCommentsChangesGit/SVN commitsRelated reports
 [2015-12-24 19:52 UTC] bugs dot php dot net at ss dot st dot tc
-Status: Open +Status: Closed
 [2015-12-24 19:52 UTC] bugs dot php dot net at ss dot st dot tc
(sorry, wrong test script, closing)
 [2015-12-24 21:39 UTC] requinix@php.net
-Status: Closed +Status: Not a bug
 
PHP Copyright © 2001-2026 The PHP Group
All rights reserved.
Last updated: Wed Oct 07 17:00:02 2026 UTC