Why does current() skip over first array element in a foreach() statement?

foreach, php

Solution

Possible dup of: Why does PHP's foreach advance the pointer of its array (only) once?

Right after initializing your array, you'll notice that the current index is `0`.

$arr = array(0,1,2,3);
echo current($arr); // outputs 0

When you enter into your foreach, it increments the internal array pointer by 1, making the "current" value `1`.

Notice how the array is passed to the `current()` function by reference (http://php.net/manual/en/function.current.php). This causes the behavior your are experiencing.

If you'd like to get the key of the array, you could change your foreach to something like:

foreach($arr as $key => $i)
{

}

Problem

This code outputs: 1 1 1 1 I expected either 0 0 0 0 or 0 1 2 3 ``` <?php $arr = array(0,1,2,3); foreach($arr as $i) { echo current($arr), ' '; } ?> ```

Original source

Related problems