简体   繁体   中英

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:

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM