$pie = array('Apple' => 1, 'Cherry' => 3, 'Pumpkin' => 6);
reset($pie);
while (list($k, $v) = each($pie)) {
echo "$k => $v
";
$desserts[]=$pie;
}
If the $desserts[]=$pie
line is commented out, this code block executes as expected.
Why when it is uncommented does it go into an infinite loop?
I do not understand why that happens. This is a perfect example of what NOT to do, but I don't understand why the complete array is printed over and over. I thought just the first slice would be repeated.
In the manual, it warns you not to do what you're doing.
Caution: Because assigning an array to another variable resets the original arrays pointer, our example above would cause an endless loop had we assigned
$fruit
to another variable inside the loop.
You can achieve the same results using array_fill if you just wanted to make many copies of $pie
.
$desserts = array_fill(0,count($pie),$pie);
You can avoid this loop by using a foreach
loop instead of the while
loop:
$pie = array('Apple' => 1, 'Cherry' => 3, 'Pumpkin' => 6);
foreach($pie as $k => $v){
echo "$k => $v
";
$desserts[]=$pie;
}
$pie = array('Apple' => 1, 'Cherry' => 3, 'Pumpkin' => 6);
reset($pie);
while (list($k, $v) = each($pie)) {
echo "$k => $v
";
$desserts[]=$pie;
}
Doesn't make that much sense. You're basically duplicating the $pie array for each entry in $pie.
Using foreach would be safer. Would the sample below reflect more closely the intended result perhaps?
$pie = array('Apple' => 1, 'Cherry' => 3, 'Pumpkin' => 6);
$desserts = array();
foreach($pie as $fruit => $count){
$dessert = array(
'fruit' => $fruit,
'count' => $count
);
$desserts[] = $dessert;
}