Ampersand before the variable in foreach loop
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
This means it is passed by reference instead of value... IE any manipulation of the variable will affect the original. This differs to value where any modifications don't affect the original object.
This is asked many times on stackoverflow.
It is used to apply changes in single instance of array to main array..
As:
//Now the changes wont affect array $wishesarray
foreach ($wishesarray as $id => $categoriy) {
$categoriy++;
}
print_r($wishesarray); //It'll same as before..
But Now changes will reflect in array $wishesarray also
foreach ($wishesarray as $id => &$categoriy) {
$categoriy++;
}
print_r($wishesarray); //It'll have values all increased by one..
链接地址: http://www.djcxy.com/p/10208.html
上一篇: 感叹号在PHP中意味着什么?
下一篇: 在foreach循环中的变量前加上&符号