开发者

php ::Array references

开发者 https://www.devze.com 2023-01-18 09:36 出处:网络
any idea why foreach ($groups as &$group) $group = trim(str_replace(\',\', \'\', $group)); echo \'<pre>\';

any idea why

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

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

$groupsq 开发者_JAVA百科= $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?


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.


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

0

精彩评论

暂无评论...
验证码 换一张
取 消