Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

foreach

php

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), ' ';
}
?>
like image 749
shadesbelow Avatar asked Dec 06 '12 00:12

shadesbelow


1 Answers

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)
{

}
like image 148
jchapa Avatar answered Oct 30 '22 10:10

jchapa