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), ' ';
}
?>
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)
{
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With