1

Possible Duplicate:
Strange behavior Of foreach
Strange behaviour after loop by reference - Is this a PHP bug?

Can anybody explain me why this code:

<pre>
<?php

$a = array('page', 'email', 'comment');
$b = array('page' => 'realpage', 'email' => 'reaLmail', 'comment' => 'c');
$c = array();

foreach ($a as &$item) {
        if (isset($b[$item])) {
               $item =  $b[$item];
        }
}


foreach ($a as $item) {
        $c[] = $item;
}

print_r($c);

Outputs

 Array
(
    [0] => realpage
    [1] => reaLmail
    [2] => reaLmail
)

??? Why BEFORE second loop a is (by var_dump)

array(3) {
  [0]=>
  string(8) "realpage"
  [1]=>
  string(8) "reaLmail"
  [2]=>
  &string(1) "c"
}

But in first iteration, a is

 array(3) {
  [0]=>
  string(8) "realpage"
  [1]=>
  string(8) "reaLmail"
  [2]=>
  &string(8) "realpage"
}

and on second and third [1] and [2] indexes are the same "reaLmail", and [2] is pointer? Thank you!

Community
  • 1
  • 1
Guy Fawkes
  • 2,313
  • 2
  • 22
  • 39
  • BTW, there are no pointers in PHP (in userland at least), `&` is the reference operator (they're similar in C++, but not the same thing). – John Carter May 05 '12 at 11:08
  • if you place `var_dump($a);` after first `foreach` you'll see that last item of array is actually a poiner. So last ` $c[] = $item;` doesn't work and `$item` remains the same from previous iteration. – s.webbandit May 05 '12 at 11:08

2 Answers2

1

if you use foreach (... as &..), then unset is required as describe in the php manual:

foreach ($a as &$item) {
        if (isset($b[$item])) {
               $item =  $b[$item];
        }
}
unset($item);
meze
  • 14,975
  • 4
  • 47
  • 52
0

You don't need the & in the first loop, which makes it a reference. Remove it, and your example should work fine.

foreach ($a as &$item)
Nadh
  • 6,987
  • 2
  • 21
  • 21