The difference between PHP object array and general array

(*-*)浩
Release: 2023-02-26 21:00:01
Original
2784 people have browsed it

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 "<br/>";
 }    // 结果:1 2 3
Copy after login

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 = &#39;张三&#39;;

$bb = new stdClass();
$bb->name =  &#39;李四&#39;;

$arr = array($aa, $bb);

foreach($arr as $element){
    $element->name = &#39;qqyumidi&#39;;
}

foreach($arr as $el){
    echo $el->name;
    echo "<br/>";
}      // 结果:qqyumidi   qqyumidi
Copy after login

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!

Related labels:
php
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!