Forum Moderators: coopster
$test['one'] = 'foo';
$test['two'] = 'bar';
$test['three'] = 'die';
$test[0] = 'this is zero';
$test[12] = 'this is after the zero key';
Traversing the array with
while (list($key, $value) = each($test)) {
echo "$key is $value<BR>\n";
}
one is foo
two is bar
three is die
is this is zero
12 is this is after the zero key
for(reset($test);$key=key($test);next($test)){
echo "$key is {$test[$key]} <br />";
}
one is foo
two is bar
three is die
If I'm reading this correctly, it appears if an array has a key of "0", the key function will return false. Is this "correct" php behavior?
The real problem: I've been using reset/key/next to traverse associative arrays for a while now, because I am old and slow to change. I've just run into a bug because I didn't know a zero key would "kill" the reset/key/next loop. Getting rid of the 0 index would require a huge code rewrite.
Obviously, the best answer is to use the while/list/each format. However, I am lazy, and don't want to go through all my code, replacing loops. I was wondering if anyone knew of a way to "fix" the reset/key/next loop to recognize a 0 index so I could only make one global code change (php.ini setting, some magic override, etc.)
I realize I'm probably SOL, but thought I'd check here first before I start the tedious loop fixing.