Is there any special rule for using foreach and while loop (using the each () function) to iterate over an array in php?

I am new to PHP. My question is when I use the following script:

$arr1 = array('fname' => 'niraj','lname' => 'kaushal','city' => 'lucknow');

while(list($key, $value) = each($arr1)){

echo "$key has $value value <br>";

}

foreach($arr1 as $key => $value){

echo "$key:$value <br>";

}

displays

fname has niraj value 
lname has kaushal value 
city has lucknow value 
fname:niraj 
lname:kaushal 
city:lucknow

but when I change the order of foreach and while, as follows

$arr1 = array('fname' => 'niraj','lname' => 'kaushal','city' => 'lucknow');

foreach($arr1 as $key => $value){

echo "$key:$value <br>";

}

while(list($key, $value) = each($arr1)){

echo "$key has $value value <br>";

}

he gives the following conclusion

fname:niraj 
lname:kaushal 
city:lucknow 

Why the second script does not display the output of the while loop. What is the reason for this.

+4
source share
1 answer

This is because it each()returns only the current key / value, and then advances the internal counter (where in the array you are currently in). It does not reset it.

(foreach) , , .

reset() each():

reset($arr1);
while (list($key, $value) = each($arr1)){
    echo "$key has $value value <br>";
}
+7

Source: https://habr.com/ru/post/1609918/


All Articles