简体   繁体   中英

PHP traverse array with zero values

I am using the following loop to traverse an array where i need both the value and the key field.

while ($value = current($a)) {

echo "$value ".key($a).'<br />';
next($a);
}

The problem is that the traversal only takes place till a '0' is encountered in the array as the while statement says.Is there any way i can traverse array with zero values(size of array varies) and get both value and key.

Use key instead of current for the looping condition and compare its value to null :

The key() function simply returns the key of the array element that's currently being pointed to by the internal pointer. It does not move the pointer in any way. If the internal pointer points beyond the end of the elements list or the array is empty, key() returns NULL .

while (($key = key($a)) !== null) {
    $value = value($a);
    echo "$value $key<br />";
    next($a);
}

But a far more convenient way would be using foreach instead:

foreach ($a as $key => $value) {
    echo "$value $key<br />";
}

just use a foreach -loop:

foreach($a as $key => $value) {

  echo "$value $key <br />";

}

it's much simpler and sounds exactly like what you're looking for.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM