简体   繁体   中英

Strange foreach loop after modifying array

As I wrote some code, PHP confused me a little as I didn't expected the result of the following code:

$data = array(array('test' => 'one'), array('test' => 'two'));

foreach($data as &$entry) {
    $entry['test'] .= '+';
}

foreach($data as $entry) {
    echo $entry['test']."\n";
}

I think it should output

one+
two+

However the result is: http://ideone.com/e5tCsi

one+
one+

Can anyone explain to me why?

This is expected behaviour, see also https://bugs.php.net/bug.php?id=29992 .

The reference is maintained when using the second foreach, so when using the second foreach the value of $entry , which points still to $data[1] , is overwritten with the first value.

Ps (thanks to @billyonecan for saying it): you need to unset($entry) first, so that your reference is destroyed.

This is mentioned specifically in the documentation for foreach . You should unset the loop variable when it gets elements of the array by reference.

Warning

Reference of a $value and the last array element remain even after the foreach loop. It is recommended to destroy it by unset().

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