在foreach循环中更改集合的元素

时间:2011-03-22 23:19:21

标签: php foreach

我可以在PHP中执行以下操作吗?

foreach ($collection as &$element)
    $element = ...

1 个答案:

答案 0 :(得分:1)

几乎 - 你应该删除%。这是一个在PHP 5.3.4本地工作的例子:

$foo = array("1" => "First", "2" => "Second");

foreach($foo as $key => & $element) {
    $element = $element . " With More Text Attached!\n";
}

print_r($foo);

导致

Array ( 
   [1] => First With More Text Attached! 
   [2] => Second With More Text Attached! 
)