Array pointer problems

Source: Internet
Author: User
Array pointer & lt ;? Php $ arr & nbsp ;=& nbsp; array ('id' = & gt; 1, 'title' = & gt; 'test 1 ',), array ('id' = & gt; 2, 'title' = & gt; 'test 2',), array ('id' = & array pointer


$ Arr = array (
Array (
'Id' => 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? To learn how to do this from 1, please share with us: 1, 'title' => 'test 1',), array ('id' => 2, 'title' => 'test 2... 'data-pics = ''>
------ 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.
------ Solution --------------------
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.
------ Solution --------------------
Use do instead, because while is the pointer that previously moved one
 $ Arr = array (
Array (
'Id' => 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 ));



?>


Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.