Alex Rivera | Logout

PHP - Ampersand before the variable in foreach loop

Asked 2012-01-07T11:24:08.490
67

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

    }
}
Edit
Report

2 Answers

85

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

answered 2012-01-07T11:33:11.173
9

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..
answered 2012-01-07T11:31:45.737

Your Answer