Array pointer problems
1, 'title' => 'test 1',), array ('id' => 2, 'title' => 'test 2 ',), array ('id' => 3, 'title' => 'test 3',), array ('id' => 4, 'title' => 'test 4',), array ('id' => 5, 'title' => 'test 5 ',),); while (list ($ k, $ v) = each ($ arr) {print_r (current ($ arr); echo'
';}
Loop a two-dimensional array and use current to return the current element. Why does it start with 2nd elements? If you want to start from 1, please advise
Reply to discussion (solution)
When you first execute the while (list ($ k, $ v) = each ($ arr) here (note: each -- returns the current key/value pair in the array and moves the array pointer one step forward)
That is to say, each ($ arr) has moved the pointer of $ arr array one by one.
So it starts with 2nd elements.
Let's start with the first one:
Do
{
Print_r (current ($ arr ));
Echo'
';
}
While (list ($ k, $ v) = each ($ arr ));
Hope to help you.
The current function returns the current array unit... During the first while judgment, each has pointed the array unit to the next position .. As a result, the Cup starts from 2.
Use do instead, because while is the pointer that previously moved one
1, 'title' => 'test 1',), array ('id' => 2, 'title' => 'test 2 ',), array ('id' => 3, 'title' => 'test 3',), array ('id' => 4, 'title' => 'test 4',), array ('id' => 5, 'title' => 'test 5 ',),); do {print_r (current ($ arr); echo'
';} While (list ($ k, $ v) = each ($ arr);?>
Why not use while (list ($ k, $ v) = each ($ arr) instead of foreach?