Ampersand before a variable in foreach php

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.


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


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:

  • http://www.php.net/manual/en/language.references.pass.php
  • Are PHP Variables passed by value or by reference?
  • http://www.learncpp.com/cpp-tutorial/73-passing-arguments-by-reference/ (this is for C++, but the same principle applies in PHP)
  • 链接地址: http://www.djcxy.com/p/59554.html

    上一篇: 混淆空,isset,!空,!isset

    下一篇: 在foreach中的一个变量之前的&符号