1

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?

2 Answers 2

1

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.

3
  • 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) Commented Oct 4, 2010 at 1:04
  • @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. Commented Oct 4, 2010 at 1:22
  • 3
    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. Commented Oct 4, 2010 at 6:06
1

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

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.