foreach in PHP is a frequently used function and is often used to traverse arrays. For situations where the elements in the array are values (such as common types of arrays), foreach just adds each element in the array to The value is copied to the variable after each, which is a copy of the value itself. Changing its value will not affect the array itself.
## Such as: (Recommended learning: PHP video tutorial)
$arr = array(1, 2, 3); foreach($aa as $el){ $el =+ 100; } foreach($arr as $el){ echo $el; echo "<br/>"; } // 结果:1 2 3
But if it is an object array, that is, when the array elements are all objects, the variable after each is a copy of the object reference, and changes to it will directly affect the original array itself. This is easily confused with the above situation.
Such as:
$aa = new stdClass(); $aa->name = '张三'; $bb = new stdClass(); $bb->name = '李四'; $arr = array($aa, $bb); foreach($arr as $element){ $element->name = 'qqyumidi'; } foreach($arr as $el){ echo $el->name; echo "<br/>"; } // 结果:qqyumidi qqyumidi
The above is the detailed content of The difference between PHP object array and general array. For more information, please follow other related articles on the PHP Chinese website!