我在这里做错了什么?这很简单,我忽略了一些东西。我试图在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);
阵列保持不变。
答案 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);