foreach 通过在 $value 之前加上 很容易就能修改数组的单元,在 foreach 使用引用时要注意了。也可以在处理完后立即断开引用关系,后面就不会有上述情况了。
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);

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

SublimeText3 English version
Recommended: Win version, supports code prompts!

SecLists
SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.

VSCode Windows 64-bit Download
A free and powerful IDE editor launched by Microsoft

EditPlus Chinese cracked version
Small size, syntax highlighting, does not support code prompt function