php.net |  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.
(description)
Block user comment
Status: Assign to:
Package:
Bug Type:
Summary:
From: lucasbarrena at hotmail dot com
New email:
PHP Version: OS:

 

 [2017-09-13 07:08 UTC] 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.


Patches

Add a Patch

Pull Requests

Add a Pull Request

History

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] requinix@php.net
-Status: Open +Status: Not a bug
 [2017-09-13 12:18 UTC] requinix@php.net
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.
 
PHP Copyright © 2001-2024 The PHP Group
All rights reserved.
Last updated: Thu Apr 25 22:01:29 2024 UTC