Home > Backend Development > PHP Tutorial > Foreach reference passes address in PHP

Foreach reference passes address in PHP

小云云
Release: 2023-03-22 06:16:02
Original
3190 people have browsed it

This article mainly shares with you the foreach reference transfer address in PHP. Understanding this problem requires three points of knowledge. I hope it can help everyone.

1 Normal assignment and reference assignment in php

The variable name is stored in the memory stack. It points to the address of the specific memory in the heap. Find the memory in the heap through the variable name;

Ordinary value passing, after passing the value, it is a different address name, pointing to a different memory entity;

Reference passing by value, after passing the reference, it is a different address name, but they all point to the same memory entity ;Change one of them, and the other one will also be changed;

This is probably the relationship. For details, you can look at this https://www.cnblogs.com/mushan/p /4330386.html


2 The scope of variables

Variables defined outside all functions have the global scope; Variables defined inside a function are used in the local scope. Global variables can be accessed from anywhere in the script, but to access global variables within a function, use the global keyword. Local variables can only be accessed inside the function.

3  foreach
$arr = array(1,2,3);
foreach($arr as &$v){}
$v 变量未销毁    $arr[2] 与 $v保持索引关系(数组组后一个元素)
foreach ($arr as $v){}
$v 每次获得新值
$arr=array(1,2,&$v); $v=1 数组为 array(1,2,1); 
$arr=array(1,2,&$v); $v=2 数组为 array(1,2,2); 
第三次遍历数组为 array(1,2,2); 
所以结果为 array(1,2,2);
Copy after login

The above is the detailed content of Foreach reference passes address in PHP. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
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