且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

PHP - 在foreach循环中的变量之前的和号

更新时间:2022-10-15 18:43:27

例子会显示你的区别

  $ array = array(1,2); 
foreach($ array为$ value){
$ value ++;
}
print_r($ array); // 1,2,因为我们迭代了
$ b foreach($ array as& $ value){
$ value ++;
}
print_r($ array); // 2,3,因为我们迭代了对数组

的实际值的引用。查看PHP文档这里: http://pl.php.net/manual/en/ control-structures.foreach.php

Possible Duplicate:
Reference - What does this symbol mean in PHP?

I need to know why we use ampersand before the variable in foreach loop

foreach ($wishdets as $wishes => &$wishesarray) {
    foreach ($wishesarray as $categories => &$categoriesarray) {

    }
}

Thanks

This example will show you the difference

$array = array(1, 2);
foreach ($array as $value) {
    $value++;
}
print_r($array); // 1, 2 because we iterated over copy of value

foreach ($array as &$value) {
    $value++;
}
print_r($array); // 2, 3 because we iterated over references to actual values of array

Check out the PHP docs for this here: http://pl.php.net/manual/en/control-structures.foreach.php