Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why can't I unset a variable in a `foreach` loop?

Tags:

php

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?

like image 248
Daniel Pairen Avatar asked Dec 09 '22 23:12

Daniel Pairen


1 Answers

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
)
like image 52
nickb Avatar answered Dec 28 '22 07:12

nickb