A little understanding of foreach loops

Source: Internet
Author: User
Therefore, in the normal programming process, in order to reduce the use of variables and simplify the code, the foreach will no longer use the source array, you can consider foreach to determine that the single array extracted in the body is named with the same name as the source array.

First, let's look at a piece of code:

$ Arr = array ("a", "B", "c", "d ");
Foreach ($ arr as $ val ){
Echo $ val .'';
$ Arr = array ("a1", "b1", "c1", "d1 ");
Foreach ($ arr as $ val ){
Echo $ val .'';
}
}


What will this code output?
Or a simple one:

$ Arr = array ("a", "B", "c", "d ");
Foreach ($ arr as $ val ){
Echo $ val .'';
$ Arr = array ();
}

The first code outputs "a a1 b1 c1 d1 B a1 b1 c1 d1 c a1 b1 c1 d1 d a1 b1 c1 d1", and the second code outputs "a B c d ".
Why? When I first read this code with my colleagues, I thought it would output "a a1 b1 c1 d1 a1 b1 c1 d1 ...", However, the results are indeed incorrect. In fact, if we think of a loop, it would be an endless loop ..
After checking the relevant information, I realized that the foreach loop array is actually a copy of the source array. that is to say, foreach copied the source array at the beginning of the first loop, when the source array is modified in the loop body, the foreach is not changed.
Therefore, in the normal programming process, in order to reduce the use of variables and simplify the code, the foreach will no longer use the source array, you can consider foreach to determine that the single array extracted in the body is named with the same name as the source array.
That is, like this:

$ Array = array (1, 2, 3, 4, 5, 6, 7 );
Foreach ($ array as $ array ){
Echo $ array;
}

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.