1

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?

2 Answers 2

3

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.

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

Sign up to request clarification or add additional context in comments.

1 Comment

+1 - Side Note: You can break the binding between the variable and content by using unset() - php.net/manual/en/language.references.unset.php
0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.