PHP - Ampersand before the variable in foreach loop [duplicate]
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) {
}
}
Solution 1:
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
Solution 2:
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.
Solution 3:
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..
Solution 4:
For the code in your question, there can be no specific answer given because the inner foreach loop is empty.
What I see with your code is, that the inner foreach
iterates over a reference instead of the common way.
I suggest you take a read of the foreach
PHP Manual page, it covers all four cases:
foreach($standard as $each);
foreach($standard as &$each); # this is used in your question
$reference = &$standard;
foreach($reference as $each);
$reference = &$standard;
foreach($reference as &$each); # this is used in your question