|  support |  documentation |  report a bug |  advanced search |  search howto |  statistics |  random bug |  login
Bug #75200 problem with array, foreach and reference
Submitted: 2017-09-13 07:08 UTC Modified: 2017-09-13 12:18 UTC
From: lucasbarrena at hotmail dot com Assigned:
Status: Not a bug Package: Arrays related
PHP Version: 7.1.9 OS: Windows
Private report: No CVE-ID: None
View Add Comment Developer Edit
Welcome! If you don't have a Git account, you can't do anything here.
You can add a comment by following this link or if you reported this bug, you can edit this bug over here.
Block user comment
Status: Assign to:
Bug Type:
From: lucasbarrena at hotmail dot com
New email:
PHP Version: OS:


 [2017-09-13 07:08 UTC] lucasbarrena at hotmail dot com
The code is very simple and speaks for itself.

Test script:
$data = array(array('name' => 'Lucas', 'surname' => 'Barrena'));

foreach($data as &$row) {} #here, with reference
#unset($row); #this line, fix everything

$copy = $data;


#set, method A
$data = array(array('name' => 'Lcs'));

#method A-1: works
#without foreach

#method A-2: fails
foreach($data as $row) {}

#method B, fails
#$data[0]['name'] = 'Lcs';
#without foreach

print '<br>';
print_r($copy); #now copy it's different with methods fails

Expected result:
$copy should not be different.


Add a Patch

Pull Requests

Add a Pull Request


AllCommentsChangesGit/SVN commitsRelated reports
 [2017-09-13 07:28 UTC] spam2 at rhsoft dot net
what about making two distinct real code samples for both cases so that somebody has a chance to understand the problem (including the desired output)
 [2017-09-13 12:18 UTC]
-Status: Open +Status: Not a bug
 [2017-09-13 12:18 UTC]
Thank you for taking the time to write to us, but this is not
a bug. Please double-check the documentation available at and the instructions on how to report
a bug at Big red warning

$row is still a reference after the foreach. It references the last element of $data, which will also be a reference. $copy=$data means $copy will get a copy of the reference.

$row, $data[0], and $copy[0] are all references of the same value.
PHP Copyright © 2001-2020 The PHP Group
All rights reserved.
Last updated: Sun Mar 29 09:01:24 2020 UTC