Detailed analysis of foreach in PHP-General array and object array

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.