1

I have seen an ampersand symbol before a variable in foreach. I know the ampersand is used for fetching the variable address which is defined earlier.

I have seen a code like this:

<?php
$arr = array(1, 2, 3, 4);
foreach ($arr as &$value) {
    $value = $value * 2;
}

// $arr is now array(2, 4, 6, 8)
unset($value); // break the reference with the last element

?>

I just need to know the use of & before $value. I haven't seen any variable declared before to fetch the variable address.

Please help me why its declared like this. Any help would be appreciated.

Chris Forrence
  • 10,042
  • 11
  • 48
  • 64
user3220407
  • 41
  • 1
  • 5

2 Answers2

3

The ampersand in the foreach-block allows the array to be directly manipulated, since it fetches each value by reference.

$arr = array(1,2,3,4);
foreach($arr as $value) {
    $value *= 2;
}

Each value is multiplied by two in this case, then immediately discarded.


$arr = array(1,2,3,4);
foreach($arr as &$value) {
    $value *= 2;
}

Since this is passed in by reference, each value in the array is actually altered (and thus, $arr becomes array(2,4,6,8))

Chris Forrence
  • 10,042
  • 11
  • 48
  • 64
0

The ampersand is not unique to PHP and is in fact used in other languages (such as C++). It indicates that you are passing a variable by reference. Just Google "php pass by reference", and everything you need to explain this to you will be there. Some useful links:

Community
  • 1
  • 1
Geoff
  • 2,461
  • 2
  • 24
  • 42