foreach in PHP is often used as a function to iterate over an array, and for a case where the elements in the array are values (such as an array of common types), foreach simply copies the values of each element in the array to the variable following each.
That is, a copy of the value itself , which changes its value without affecting the array itself.
Such as:
$arr = (1, 2, 3); foreach ( $aa as $el =+ 100;} foreach ( $arr as $el ) { echo $el echo "<br/>" ;} // results: 1 2 3
However, if the case of an array of objects, that is, the array elements are objects, then the variables after each are copies of the object reference , and changes to it will directly affect the original array itself. This is easily confused with the situation above.
Such as:
$aa=NewStdClass ();$aa->name = ' Zhang San ';$BB=NewStdClass ();$BB->name = ' John Doe ';$arr=Array($aa,$BB);foreach($arr as $element){ $element->name = ' Mrxia ';}foreach($arr as $el){ Echo $el-name; Echo"<br/>";} //results: Mrxia mrxia
Detailed analysis of foreach in PHP-General array and object array