note 68494 deleted from function.each by nicobn

[email protected] Fri, 18 Feb 2011 08:07:46 -0800
Newsgroups php.notes
Message-ID <[email protected]>
Note Submitter: Michael 

----

Something that I found useful to note is that each() does NOT return a reference to the array contets, but a copy of the item.

So, say you have:
$boxes = Array();
$boxes["Large"] = Array();
$boxes["Medium"] = Array();
$boxes["Small"] = Array();

and want to put the small box inside the medium box inside the large box, doing:

$lastBox = NULL;
while (list($key, $box) = each($boxes)) {
  if (isset($lastBox))
    $lastBox[0] =& $box;
  $lastBox =& $box;
}

will not work.  Instead, you have to use the key like:

$lastBox = NULL;
while (list($key) = each($boxes)) {
  $box =& $boxes[$key];
  if (isset($lastBox))
    $lastBox[0] =& $box;
  $lastBox =& $box;
}

which will work.