PHP: Removing an Element From an Array during foreach

PHP: Removing an Element From an Array during foreach

Categorised in:

foreach – What does it do?

The foreach control structure is a simple way of traversing (or iterating through) every element of an array or object. It has two control structures, namely:

foreach( $array as $a )

and

foreach( $array as $key=>$value )

In the first you have a variable $a which is given the value of the first element of the array, followed by each subsequent element as the array is traversed. In the second, you’ve still got the value ($value) but also the key of the array($key). This is real useful.

I just wondered what happens if you remove an element from an array whilst traversing an array using foreach?

So I wrote this routine:

$rdrr = array("a" => "apple", "b" => "banana", "c" => "cherry", "d"=>"date");
foreach( $rdrr as $key=>$value ) {
	  if( $key == "b" ) unset( $rdrr["c"] );
	  echo "$key : $value";
}
print_r ( $rdrr );

We have an array $rdrr and start to traverse it with the foreach, but when we’re at element ‘b’, we remove element ‘c’. Question is, does the foreach still traverse to ‘c’ or go straight to ‘d’?

Answer

a : apple
b : banana
c : cherry
d : date
Array ( [a] => apple [b] => banana [d] => date ) 

So, no, although the element is removed from the array (as can be seen from print_r), the foreach cycles through each element in the array as it was before the loop.

Leave a Reply

Your email address will not be published. Required fields are marked *

Tagged with ,

Available Tags

api finder foreach functions json oscommerce php programming sudoku themes webp wordpress