4

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?

5

3 Answers 3

8

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
)
Sign up to request clarification or add additional context in comments.

Comments

4

The foreach executes on a copy of the array, not a reference, to make it easier to deal with more drastic changes in the array (such as yours) during execution.

Comments

2

foreach iterates over the array and assigns the key to $i and the value to $a before accessing the code block inside the loop. The array is actually "copied" by the function before being iterated over, so any changes to the original array does not affect the progression of the loop.

You can also pass the $array by reference into the foreach using $i => &$a instead of by value which will allow the mutation of the array.

Another option would be to work directly on the array, and you would see something different:

for($x=0;$x<count($array);$x++){
    unset($array[1]);
    // for $x=1 this would result in an error as key does not exist now
    echo $array[$x];
}

print_r($array);

Of course, this assumes that your array is numerically and sequentially keyed.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.