What’s wrong with each()?

The each($array)function skips the first element of the array, and after the last one it passes “idle” again. The array is created automatically with different string keys.

If $array ('title' => 'blabla', 'value' => 'blabla', 'sTitle' => 'blabla')

each($array)
echo ' !: '.key($array);

Output:

!: value !: sTitle !:

What’s the matter? What is the correctway to solve the problem?


Answer 1, authority 100%

foreach($array as $key=>$value){
  echo ' !: '.$key' !: '.$value;
}

Answer 2, authority 100%

Clearly confusion between eachand foreach.

It should either be like this:

while (list($key, $val) = each($array)) {
    echo "$key => $val\n";
}

Either like @knessaid. But! the key()function does not shift the pointer. It is offset after the first “idle” eachcall, so the last eachhas already gone beyond the array, and keyreturns an empty value.