php.net |  support |  documentation |  report a bug |  advanced search |  search howto |  statistics |  random bug |  login
Bug #35485 foreach is not working correctly
Submitted: 2005-11-30 12:41 UTC Modified: 2005-11-30 14:05 UTC
From: vma1 at abv dot bg Assigned:
Status: Not a bug Package: Arrays related
PHP Version: 5CVS-2005-11-30 (snap) OS: Slackware 10.1, kernel 2.4.31
Private report: No CVE-ID: None
Welcome back! If you're the original bug submitter, here's where you can edit the bug or add additional notes.
If you forgot your password, you can retrieve your password here.
Password:
Status:
Package:
Bug Type:
Summary:
From: vma1 at abv dot bg
New email:
PHP Version: OS:

 

 [2005-11-30 12:41 UTC] vma1 at abv dot bg
Description:
------------
When using foreach($arr as $index => &$item), the $item reference does not always allow a modification of the referenced element.

Reproduce code:
---------------
<?
$items = array (array (1), array (1));
foreach ($items as $index => &$one_item) {
	printf ("C1 IDENTICAL: %u\n", $items [$index] === $one_item);
	each ($items [$index]);
	printf ("C2 IDENTICAL: %u\n", $items [$index] === $one_item);
	$one_item = 678;
	printf ("C3 IDENTICAL: %u\n", $items [$index] === $one_item);
}
?>


Expected result:
----------------
C1 IDENTICAL: 1
C2 IDENTICAL: 1
C3 IDENTICAL: 1
C1 IDENTICAL: 1
C2 IDENTICAL: 1
C3 IDENTICAL: 1


Actual result:
--------------
C1 IDENTICAL: 1
C2 IDENTICAL: 1
C3 IDENTICAL: 1
C1 IDENTICAL: 1
C2 IDENTICAL: 1
C3 IDENTICAL: 0


Patches

Pull Requests

History

AllCommentsChangesGit/SVN commitsRelated reports
 [2005-11-30 12:54 UTC] tony2001@php.net
Do not modify array in the foreach() loop.

 [2005-11-30 13:19 UTC] vma1 at abv dot bg
The array is not being modified.
 [2005-11-30 13:23 UTC] vma1 at abv dot bg
In my previous comment I meant that no array elements are being added/removed. Besides try removing the each() operator and behaviour becomes correct. Something that should not happen.
 [2005-11-30 13:30 UTC] tony2001@php.net
http://php.net/each
each --  Return the current key and value pair from an array and *advance the array cursor*
 [2005-11-30 13:35 UTC] vma1 at abv dot bg
So what? each() is not touching the $items array, it is touching the $items [0], and $items [1] elements which are arrays as well.
 [2005-11-30 14:01 UTC] sniper@php.net
This is expected behaviour, no bug.
 [2005-11-30 14:05 UTC] vma1 at abv dot bg
So what language construct should I use if I want to modify all array elements inside a loop?
 
PHP Copyright © 2001-2025 The PHP Group
All rights reserved.
Last updated: Thu Jul 03 08:01:34 2025 UTC