PHP - Ampersand before the variable in foreach loop

PhpForeachReference

Php Problem Overview


> 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) {

    }
}

Php Solutions


Solution 1 - Php

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 - 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.

Solution 3 - Php

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 - Php

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionSachin SawantView Question on Stackoverflow
Solution 1 - PhpMariusz SakowskiView Answer on Stackoverflow
Solution 2 - PhpAlanFosterView Answer on Stackoverflow
Solution 3 - PhpRajat SinghalView Answer on Stackoverflow
Solution 4 - PhphakreView Answer on Stackoverflow