How a foreach traversal is a pointer problem

Source: Internet
Author: User
A foreach traversal is a copy problem for the original array

such as $a1=array (' A ', ' B ', ' C ');
foreach ($a 1 as $k = = $v) {
echo $v, '
';
if ($k ==1) {
$a 1[3] = ' d ';
}
}
Var_dump (current ($a 1));
Array A1 The Foreach traversal is a copy of the original array when the foreach traversal I want to ask if it is to copy the original array after the whole copy and then traverse or in the original array one element is copied stored in the variable $k $v save one and then echo output a flowchart that looked at the foreach execution Considered the second kind.

If I follow the second law, then when the if ($k ==1, the original array is written at this point, foreach makes a true copy of the pointer to the third element) Here I am puzzled that the execution flowchart of the foreach is done by a copy of the pointer of the original array to the storage output. And this code finally output $a1 pointer to the third element C will not move then follow my second understanding of how the pointer does not move how to complete the traversal of a foreach?

Is it so understood that it is $a1 to copy out, for example, $a2 foreach traversal is actually $a2 so that you can understand the teacher said this sentence: the array is traversing the original array of copies

Which means that the whole $a1 is copied out, and then a single element of $a2 is stored in the variable and then output?




Reply to discussion (solution)

Array has two sets of pointers, the set is you can see the subscript, the association key, the other set is the internal you can not see, but with Next, perv, end and other functions to operate
foreach simply passes in a copy of the array's internal pointers, so the array members you modify, add, and delete in foreach are not represented in foreach. Because you didn't change the copy that was passed in.

  • Related Article

    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.