问题
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