Why can't I disable the variable in the `foreach` loop?

Why can't I disable a variable in a foreach ?

 <?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 inside the foreach , but outside the loop it is not set. Is it possible to disable it in a loop?

+4
source share
3 answers

You need to pass the array by reference, for example:

 foreach($array as $i => &$a){ 

Pay attention to the added & . This is also indicated in the manual for foreach :

To be able to directly modify array elements in a loop, $ value is preceded with &. In this case, a value will be assigned to the link.

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 ) 
+8
source

foreach is executed on a copy of the array, not on the link, in order to simplify the work with more radical changes in the array (for example, yours) at runtime.

+4
source

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

You can also pass the $ array by reference in foreach, using $i => &$a instead of a value that allows mutation of the array.

Another option is to work directly with the array, and you will see something else:

 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 entered.

+2
source

All Articles