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:
Note the added
&. This is also stated in the manual for foreach:This now produces: