|
php.net | support | documentation | report a bug | advanced search | search howto | statistics | random bug | login |
[2004-09-02 14:22 UTC] tomas_matousek at hotmail dot com
Description:
------------
In the manual page describing each() function is the following caution:
"Because assigning an array to another variable resets the original arrays pointer, ..."
I think that this is a bug, although it is documented and treated as feature.
I realized that the pointer is reset when a copy of an array is made. However, PHP makes some optimizations which prevents unnecessary array copying (which is good feature).
Since these optimizations are not known for users (and shouldn't be) the behavior of inner pointer is thus non-deterministic from user's point of view.
See the follwoing code.
Its output depends on whether the statement $b[] = 1; is commented or not.
Reproduce code:
---------------
function f($a) { $b = $a; /*$b[] = 1;*/ return $b; }
$arrayOuter = array("key1","key2");
$arrayInner = array("0","1");
while(list(,$o) = each($arrayOuter))
{
$q = f($arrayInner);
while(list(,$i) = each($arrayInner))
{
print "inloop $i for $o\n";
}
}
Expected result:
----------------
inloop 0 for key1
inloop 1 for key1
Actual result:
--------------
inloop 0 for key1
inloop 1 for key1
inloop 0 for key2
inloop 1 for key2
PatchesPull RequestsHistoryAllCommentsChangesGit/SVN commits
|
|||||||||||||||||||||||||||
Copyright © 2001-2025 The PHP GroupAll rights reserved. |
Last updated: Wed Oct 22 07:00:01 2025 UTC |
I think it is mentioned in the manual that PHP uses copy-on-write technique. This means that if $a = array(1,2,3); and $b = $a; there is _only_ 1 array and $b reference this array. When change has been made the copy-on-write starts to work. AFAIK it is not only for arrays... Simple example : php -r '$a=str_repeat("a", 10000000);while ($i++<2000) ${"a".$i} = $a; This thing creates a very long string ~ 10MB, and then reference it 2000 times. If there was no copy-on-write then I will need 2*10^10 memory, which is more than a process on 32bit architecture can address.