替换foreach循环中的数组值

时间:2014-07-08 13:47:26

标签: php arrays foreach

我在这里做错了什么?这很简单,我忽略了一些东西。我试图在foreach循环中替换数组键的值:

$arr = array();
$arr['firstimg'] = '123';
$arr['secondimg'] = '456';
$arr['thirdimg'] = '789';

foreach ($arr as $key => $value) {

    if ($key == 'secondimg') { 
      $value = '000';

    } 

}

print_r($arr);

阵列保持不变。

3 个答案:

答案 0 :(得分:3)

变量$value的范围限定为循环。您需要更新$arr[$key]

的值

或者,您可以按如下方式声明循环:

foreach ($arr as $key => &$value) {

这使$value引用了原始数组值(而不是副本)。

答案 1 :(得分:1)

应该是:

foreach ($arr as $key => $value) {

    if ($key == 'secondimg') { 
      $arr['secondimg'] = '000';

    } 

}

答案 2 :(得分:0)

通过引用传递,

$arr = array();
$arr['firstimg'] = '123';
$arr['secondimg'] = '456';
$arr['thirdimg'] = '789';

foreach ($arr as $key => $value) {

    if ($key == 'secondimg') { 
      $value = '000';

    } 

}

print_r($arr);

$arr = array();
$arr['firstimg'] = '123';
$arr['secondimg'] = '456';
$arr['thirdimg'] = '789';

foreach ($arr as $key => &$value) {

    if ($key == 'secondimg') { 
      $value = '000';

    } 

}

print_r($arr);