views:

78

answers:

2

Hi guys,

any idea why

foreach ($groups as &$group)
  $group = trim(str_replace(',', '', $group));

echo '<pre>';
print_r($groups);
echo '</pre>';

$groupsq = $groups;
foreach ($groupsq as &$group)
  $group = '\'' . $group . '\'';

echo '<pre>';
print_r($groups);
echo '</pre>';

Yields

Array
(
    [0] => Fake group
    [1] => another group
    [2] => non-existent
)
Array
(
    [0] => Fake group
    [1] => another group
    [2] => 'non-existent'
)

The part i am interested in is,

Why does the second array modification effect the last item on the first array?

+1  A: 

First, you need to clean up the references after each foreach loop using unset(), like so:

foreach ($groups as &$group)
  $group = trim(str_replace(',', '', $group));

unset($group);

// ...

foreach ($groupsq as &$group)
  $group = '\'' . $group . '\'';

unset($group);

Secondly, you're printing $groups instead of $groupsq:

echo '<pre>';
print_r($groups);
echo '</pre>';

The last item of $groups is being modified because you didn't clean up the reference after the first foreach loop.

BoltClock
Cheers, I meant to print $group twice to show the difference.Why do I need to clean it up, Is the $group variable not scoped to the foreach statement? (although yes you are correct that fixed it)
Hailwood
@Hailwood: It's not. I don't know the technical bits behind why it's left there after the loop, but it's as such so you need to clean it up.
BoltClock
PHP has no block scope. Once you create a variable in a function it will continue to exist in that function until you explicitly unset it.
konforce
+1  A: 

Here is an in-depth article explaining the technical details behind this behavior: http://schlueters.de/blog/archives/141-References-and-foreach.html

Stefan Gehrig