<?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 )
?>
&是使用到reference
以上轉載於
http://php.net/manual/en/control-structures.foreach.php
我本來看不懂,後來找到了答案→
http://ccckaass.pixnet.net/blog/post/298283101-%5bphp%5d-foreach%E7%9A%84%26%28%E5%8F%83%E7%85%A7%E6%A8%A1%E5%BC%8F%29#comment-form
留言
張貼留言