Why can't I unset a variable in a foreach
loop?
<?php
$array = array(a,s,d,f,g,h,j,k,l);
foreach($array as $i => $a){
unset($array[1]);
echo $a . "\n";
}
print_r($array);
In the code, the variable is in scope within the foreach
loop, but outside the loop it's unset. Is it possible to unset it within the loop?
You need to pass the array by reference, like so:
foreach($array as $i => &$a){
Note the added &
. This is also stated in the manual for foreach:
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.
This now produces:
a
d
f
g
h
j
k
l
Array
(
[0] => a
[2] => d
[3] => f
[4] => g
[5] => h
[6] => j
[7] => k
[8] => l
)
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