Home  >  Article  >  Backend Development  >  The difference between PHP object array and general array

The difference between PHP object array and general array

(*-*)浩
(*-*)浩Original
2019-10-16 13:43:422665browse

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.

The difference between PHP object array and general array

## 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 "
"; } // 结果: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 "
"; } // 结果: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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn