Bug #75200 [Opn->Nab]: problem with array, foreach and reference

From: Date: Wed, 13 Sep 2017 12:18:45 +0000
Subject: Bug #75200 [Opn->Nab]: problem with array, foreach and reference
References: 1  Groups: php.bugs 
Request: Send a blank email to php-bugs+get-211128@lists.php.net to get a copy of this message
Edit report at https://bugs.php.net/bug.php?id=75200&edit=1 ID: 75200 Updated by: requinix@php.net Reported by: lucasbarrena at hotmail dot com Summary: problem with array, foreach and reference -Status: Open +Status: Not a bug Type: Bug Package: Arrays related Operating System: Windows PHP Version: 7.1.9 Block user comment: N Private report: N New Comment: Thank you for taking the time to write to us, but this is not a bug. Please double-check the documentation available at http://www.php.net/manual/ and the instructions on how to report a bug at http://bugs.php.net/how-to-report.php https://php.net/manual/en/control-structures.foreach.php 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. Previous Comments: ------------------------------------------------------------------------ [2017-09-13 07:28:24] 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 07:08:13] lucasbarrena at hotmail dot com Description: ------------ The code is very simple and speaks for itself. Test script: --------------- <?php $data = array(array('name' => 'Lucas', 'surname' => 'Barrena')); foreach($data as &$row) {} #here, with reference #unset($row); #this line, fix everything $copy = $data; print_r($copy); #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. ------------------------------------------------------------------------ -- Edit this bug report at https://bugs.php.net/bug.php?id=75200&edit=1

« previous php.bugs (#211128) next »