1
$pie = array('Apple' => 1, 'Cherry' => 3, 'Pumpkin' => 6);
reset($pie);
while (list($k, $v) = each($pie)) {
    echo "$k => $v\n";
    $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.

0

3 Answers 3

6

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.

See documenation for each().

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);
Sign up to request clarification or add additional context in comments.

2 Comments

Yes, this is an example of what NOT to do. I just couldn't get the behavior. If the pointer is getting reset, why then wouldn't the output be just "Apple => 1" over and over?
@Swoop PHP works with arrays in a copy when modified approach. When you use $desserts[]=$pie; the values are not actually copied to $desserts until something is changed. So reset might not happen until PHP sees that $pie and $desserts are no longer the same, and that could be when $pie hits the end of the array.
1

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\n";
    $desserts[]=$pie;
}

Comments

1
$pie = array('Apple' => 1, 'Cherry' => 3, 'Pumpkin' => 6);
reset($pie);
while (list($k, $v) = each($pie)) {
    echo "$k => $v\n";
    $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;
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.