PHP Loop Array problem

Source: Internet
Author: User

$a = Array (' Abe ', ' Ben ', ' cam '); When a foreach iterates through an array, it is actually a copy of the traversed array and points the pointer to the beginning of the copy before it starts, and, according to the cow mechanism, re-copies the cell in the array, foreach ($a as $k =>& $n) {    $n = $n; Equivalent to the following//$n =& $a [' 0 '];//$n =& $a [' 1 '];//$n =& $a [' 2 '];} Unset ($n); Good habits print_r ($a);  foreach ($a as $k = $n) {//Notice NO reference here!//k=0     & $a [2] = n = Abe   [' Abe ', ' Ben ', ' Abe ']//k=1     & $a [2] n=ben       [' Abe ', ' Ben ', ' Ben ']//k=2     & $a [2] n=cam       [' Abe ', ' Ben ', ' Ben ']   echo ' $n \ n ';} Print_r ($a);

  

$data = [' A ', ' B ', ' C ', ' d '];foreach ($data as $key = = $val) {$val = & $data [$key];} echo "<pre>";p Rint_r ($data);

  

1,php memory usage Policy at variable assignment: Copy on Write, COW, when assigning a variable value to another variable using an assignment method, because the values of the two variables are the same, the same memory is common, and when one of the variable values changes, will be re-applied to the variable value of memory, has achieved the purpose of saving memory;
When 2,foreach iterates through an array, it is actually a copy of the traversed array, and the pointer points to the beginning of the copy before it begins to traverse;
3, the position of the pointer will also be copied when the copy occurs.

PHP Loop Array problem

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.