php 便利引用数组,PHP经典数组遍历引用问题

Warning

Reference of a $value and the last array element remain even after the foreach loop. It is recommended to destroy it by unset(). Otherwise you will experience the following behavior:<?php

$arr = array(1, 2, 3, 4);

foreach ($arr as &$value) {

$value = $value * 2;

}

// $arr is now array(2, 4, 6, 8)

// without an unset($value), $value is still a reference to the last item: $arr[3]

foreach ($arr as $key => $value) {

// $arr[3] will be updated with each value from $arr...

echo "{$key} => {$value} ";

print_r($arr);

}

// ...until ultimately the second-to-last value is copied onto the last value

// output:

// 0 => 2 Array ( [0] => 2, [1] => 4, [2] => 6, [3] => 2 )

// 1 => 4 Array ( [0] => 2, [1] => 4, [2] => 6, [3] => 4 )

// 2 => 6 Array ( [0] => 2, [1] => 4, [2] => 6, [3] => 6 )

// 3 => 6 Array ( [0] => 2, [1] => 4, [2] => 6, [3] => 6 )

?>

赞助一杯咖啡☕️

本文由 widdy 创作,采用 知识共享署名4.0 国际许可协议进行许可

本站文章除注明转载/出处外,均为本站原创或翻译,转载前请务必署名

最后编辑时间为: Oct 31, 2020 at 11:25 pm

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值