search
Homephp教程php手册php foreach 使用&(与运算符)引用赋值要注意的问题

php foreach 使用&(与运算符)引用赋值要注意的问题

Jun 13, 2016 pm 12:18 PM
ampforeachphpanduseexistQuoteNoticeofwantAssignmentoperatorpassquestion

foreach 通过在 $value 之前加上 & 很容易就能修改数组的单元,如:

PHP代码

复制代码 代码如下:


foreach($arr as $value){
$value .= '4';
}


但这个用法也很容易造成错误,而且也不容易找。

看例子更直截了当:

PHP代码

复制代码 代码如下:


$arr = array('a','b','c');
$arr2 = array('d', 'e', 'f');

foreach($arr as $value){//习惯用$value或$val
$value .= '4';
}

//都处理完毕我们在页面模版输出,首先输出$arr2
foreach($arr2 as $value){//习惯用$value或$val
//echo $value;
}
//然后再这样输出 $arr;
foreach($arr as $value){//习惯用$value或$val
echo $value, "\n";
}
?>


大家看看输出的结果是否和期望的一样。这里结果是:

复制代码 代码如下:


XML/HTML代码
a4
b4
b4


结果和我期待的不一样,这个就是引用引起的问题。

在 foreach($arr as &$value) 数组遍历到最后,引用关系并没有断开,这是等同于 $value 与 $arr 的最后一个单元即 $arr[2] 引用。

再到 foreach($arr2 as $value),$value的值一直随数组单元的值变,由于引用关系没有断开,$arr[2] 的值也跟着变化。一直到$arr2遍历完,这是$value的值为f,所以$arr[2]值也为f。
这时$arr的值应为:

XML/HTML代码

复制代码 代码如下:


Array
(
[0] => a4
[1] => b4
[2] => f
)


这个和我们看到的最终输出结果又不一样。再到 foreach($arr as $value),同理,这时 $arr[2]的值也随着 $value 变化,当遍历到key为1,即$arr[1]时,$arr[2]的值也变成 $arr[1] 的值,即是 b4。然后再遍历到key为2时 $arr[2]的值又成了 $arr[2] 的值,也就是 b4 了。就是输出时的结果。

所以在 foreach 使用引用时要注意了。也可以在处理完后立即断开引用关系,后面就不会有上述情况了。

PHP代码

复制代码 代码如下:


foreach($arr as $value){
$value .= '4';
}
unset($value);

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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools