PHP foreach change array value

帅比萌擦擦* 提交于 2020-08-07 06:53:09

问题


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){

}

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


回答1:


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

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


The php manual on foreach loops




回答2:


there's a function for that, and is builtin since early version of PHP, is called array_map



来源:https://stackoverflow.com/questions/25835856/php-foreach-change-array-value

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!