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), ' ';
}
?>
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
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.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: