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;
}