在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);

阵列保持不变。


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

或者,你可以声明循环如下:

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

这使得$value成为原始数组$value的引用(而不是副本)。


应该 :

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

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

    } 

}

通过参考,

$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);
链接地址: http://www.djcxy.com/p/53017.html

上一篇: Replacing array value in foreach loop

下一篇: Split sprintf() in foreach loop