0

I have written a simple program to understand the effect of deleting an array element inside a foreach loop on that loop.I have noticed that even if i deleted the element 4 ,it still gets printed .Why is that so ?

code :

$arr2 = array(1,2,3,4,5);

foreach($arr2 as $elem)
{
    echo '<br>val : '.$elem;

    $index=array_search(4,$arr2); // search for 4 in array

    if($index != false)
    {
       echo ' index :'.$index.' ';

       unset($arr2[$index]); // delete 4 from array 
    }
}

output :

val : 1 index :3 
val : 2 
val : 3 
val : 4  // 4 gets printed !!
val : 5 
AL-zami
  • 8,902
  • 15
  • 71
  • 130

1 Answers1

2

Change the following line to:

foreach($arr2 as &$elem)

You should also read about PHP references. foreach works on a copy of your array, not the actual array.

Sotiris Kiritsis
  • 3,178
  • 3
  • 23
  • 31
  • Thus it would reference the actual data. – Sougata Bose Jun 12 '17 at 07:01
  • &$elem reference individual data.How it will effect the actual array ? – AL-zami Jun 12 '17 at 07:39
  • 1
    @AL-zami By adding ref to $elem instead of modifying the the copy of your $arr2 array created by foreach, you modify the original actual array. Hence when unset($arr2[$index]) executes, it will remove the entry you want from the original array as you expect and not from the copy. – Sotiris Kiritsis Jun 12 '17 at 07:43