foreach loop modifies an array without I want - Hack The Tech - Latest News related to Computer and Technology

Hack The Tech - Latest News related to Computer and Technology

Get Daily Latest News related to Computer and Technology and hack the world.

Sunday, March 20, 2022

foreach loop modifies an array without I want

I don't understand what happens, I have an array of associative arrays, and I want to iterate through it so I made a foreach loop but this loop modified my initial array and I don't know why, loot at the code :

  • 1st case
var_dump($modules);
$tab = $modules;
foreach ($tab as $module){
   var_dump($module);
}

The result : enter image description here

On the left, is the initial array and at the right : the different values of the array. As you can see, it doesn't show the second one item but only the one. If I show the $tab inside of the loop, it is just an array of 2 items containing twice copies of the "jojo" item .

  • 2nd case

However, if I write this :

for($i=0;$i<count($tab);$i++){
   var_dump($tab[$i]);
}

It works fine as I want enter image description here

and if I execute the for loop after the foreach loop the result is the same as the 1st case. Do you knwo why ?



source https://stackoverflow.com/questions/71540770/foreach-loop-modifies-an-array-without-i-want

No comments:

Post a Comment