Forum Moderators: coopster

Message Too Old, No Replies

abstract php question

key() and 0 indexes

         

gliff

4:26 pm on Mar 29, 2005 (gmt 0)

10+ Year Member



Question in the abstract. We have a PHP array.

$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";
}

produces the following

one is foo
two is bar
three is die
is this is zero
12 is this is after the zero key

Traversing the array with

for(reset($test);$key=key($test);next($test)){
echo "$key is {$test[$key]} <br />";
}

produces the following

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.

jollymcfats

4:42 pm on Mar 29, 2005 (gmt 0)

10+ Year Member



The problem is that "0" is equivalent to false in a conditional expression. The fix is to change the test to compare the return of key() to null instead:

for (reset($test); ($key=key($test))!== null; next($test) ) {