Greg
Greg

Reputation: 167

Why the following PHP code creates an infinite loop?

$arr = array('a' => 1, 'b' => 2, 'c' => 3);
reset($arr);
while (list($k, $v) = each($arr)) {
    print "$k => $v\n";
    $h[] = $arr;
}

Upvotes: 0

Views: 115

Answers (2)

Jo Ker
Jo Ker

Reputation: 11

ThiefMaster is right. With the assignment of $arr you reset the internal pointer when you're at the last element. When using foreach() you will work with a copy of the original array.

Upvotes: 0

ThiefMaster
ThiefMaster

Reputation: 318518

Use foreach($arr as $k => $v) instead of reset($arr); while(...)

The reason why it's failing is that $h[] = $arr; resets the internal array pointer if it's at the end and thus the loop starts from the beginning.

Upvotes: 2

Related Questions