php.net |  support |  documentation |  report a bug |  advanced search |  search howto |  statistics |  random bug |  login
Bug #39307 foreach call by reference BUG
Submitted: 2006-10-30 14:19 UTC Modified: 2006-10-30 14:37 UTC
From: lolitka at gmail dot com Assigned:
Status: Not a bug Package: Unknown/Other Function
PHP Version: 5.1.6 OS: Windows XP
Private report: No CVE-ID: None
 [2006-10-30 14:19 UTC] lolitka at gmail dot com
Description:
------------
RUN this and see the output .... prety serious BUG i think

Reproduce code:
---------------
<?
$lines[0]="a;1";
$lines[1]="b;1";
$lines[2]="c;1";
$lines[3]="d;1";

print_r($lines);
foreach ($lines as $line_num => &$line) {
	$cell = explode(";", $line);
	$cell[1] = str_replace('1', '2', $cell[1]);
	$line = implode (";", $cell);
}

print_r($lines);
echo ("<br/>");

foreach ($lines as $line_num => $line) {
	echo $line_num." = ".$line."<hr>";
}
?>

Expected result:
----------------
last line shloud be last line ...

Actual result:
--------------
last line is taken from line before previous line

Patches

Add a Patch

Pull Requests

Add a Pull Request

History

AllCommentsChangesGit/SVN commitsRelated reports
 [2006-10-30 14:37 UTC] tony2001@php.net
Expected behaviour.
You're using the same variable in foreach-by-ref and then in foreach again, when it still points to the last element of the array.
Change $line to something else in the second foreach() and it's gone.
 
PHP Copyright © 2001-2024 The PHP Group
All rights reserved.
Last updated: Wed Apr 24 09:01:28 2024 UTC