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 :)
PHP Array foreach is a construct in PHP that allows to iterate over arrays easily. In this tutorial, we will learn the syntax of foreach loop construct and go through following scenarios
PHP Array foreach is a construct in PHP that allows to iterate over arrays easily. In this tutorial, we will learn the syntax of foreach loop construct and go through following scenarios foreach loop to iterate over PHP array of numbers.
Note that foreach does not modify the internal array pointer, which is used by functions such as current () and key () . It is possible to customize object iteration . In order to be able to directly modify array elements within the loop precede $value with &. In that case the value will be assigned by reference .
As foreach relies on the internal array pointer in PHP 5, changing it within the loop may lead to unexpected behavior. In PHP 7, foreach does not use the internal array pointer. In order to be able to directly modify array elements within the loop precede $value with &. In that case the value will be assigned by reference.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With