PHP foreach更改数组值 [英] PHP foreach change array value

查看:96
本文介绍了PHP foreach更改数组值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当您遇到如下所示的foreach循环时,我知道您可以通过$array[$key]更改数组的当前元素,但是还有一种方法可以通过$value进行更改吗?

When you have a foreach loop like below, I know that you can change the current element of the array through $array[$key], but is there also a way to just change it through $value?

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

}

这可能真的很简单,但是我对PHP还是很陌生,所以请不要为我的问题而烦恼:)

It's probably really simple, but I'm quite new to PHP so please don't be annoyed by my question :)

推荐答案

要能够直接为$value分配值,您想通过在$value之前加上&来引用$value:

To be able to directly assign values to $value, you want to reference $value by preceding it with & like this:

foreach($array as $key => &$value){
    $value = 12321; //the same as $array[$key] = 12321;
}

unset($value);

foreach循环之后,您应该执行unset($value),因为在循环之后您仍然可以访问它.
注意:当数组是变量时,只能通过引用传递$value.以下示例不起作用:

After the foreach loop, you should do unset($value) because you're still able to access it after the loop.
Note: You can only pass $value by reference when the array is a variable. The following example won't work:

foreach(array(1, 2, 3) as $key => &$value){
    $value = 12321; //the same as $array[$key] = 12321
}

unset($value);


有关foreach循环的php手册

这篇关于PHP foreach更改数组值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆