I saw this code example listed in the php manual when I was looking up each() and for a while couldn't understand how it worked, and I'm still kind of confused. I just wanted to ask for some help since it has to do with using both arrays and references.
$boxes = Array();
$boxes["Large"] = Array();
$boxes["Medium"] = Array();
$boxes["Small"] = Array();
$lastBox = NULL;
while (list($key) = each($boxes)) {
$box =& $boxes[$key];
if (isset($lastBox))
$lastBox[0] =& $box;
$lastBox =& $box;
}
As I understand it, this code takes an array of arrays, puts the last element in the middle element and then the middle element into the first element.
It sets up a while loop that goes through each of the keys of the boxes array (large, medium then small)
On the first pass where key = large, the variable $box is set to reference $boxes['large'], which is currently set to an empty array.
Since $lastbox hasn't been set yet, it is set to reference $box which references $boxes['large'] so $lastBox =& $boxes['large'];
On the second pass $box is set to reference $boxes['medium'].
Since $Lastbox is set this time, the first element of the $lastbox array (which is pointing to the same place as $boxes['large'], is set to reference $boxes['medium'].
Next $lastBox is set to reference $box which references $box['medium'] which points to an empty array.
On the final pass $box is set to reference $boxes['small']. $lastBox is set again, this time pointing to the array inside 'medium' array that was put in the first element of $boxes['large'] on the last pass. The first element of the 'medium' array becomes a reference to the 'small' array.
Sounds good, except when I do a var dump of the final $boxes variable I don't really understand what it did.
EDIT:
This is where I get confused about how the references are working. Shouldn't the first element of the boxes array ('large') contain the two other arrays? Or is it simply pointing to the values in the two other arrays.
array(3) { ["Large"]=> array(1) { [0]=> &array(1) { [0]=> &array(0) { } } } ["Medium"]=> &array(1) { [0]=> &array(0) { } } ["Small"]=> &array(0) { } }
So is it anything like this or am I completely off?
$boxes['large'][0] =& $boxes['medium']
$boxes['medium'][0] =& $boxes['small']
Perhaps this is a bad piece of code to try to figure out, maybe I'm thinking too hard, maybe i'm just stupid, but It seemed like a good way of understanding arrays and references better. I'm still lost. I don't quite get how the references work.