Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I am new in PHP. My question is that when i use 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>";

}

it outputs

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

but when i change order of foreach and while loop as follow

$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>";

}

it gives following output

fname:niraj 
lname:kaushal 
city:lucknow 

Why second script doesn't display the output of while loop. What the reason behind it.

like image 518
Niraj Kaushal Avatar asked Mar 15 '23 14:03

Niraj Kaushal


1 Answers

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

The first loop (foreach) sets the internal counter to the end of the array, so the second loop thinks it is already done and therefore does nothing.

You need to call reset() on the array before starting the loop using each():

reset($arr1);
while (list($key, $value) = each($arr1)){
    echo "$key has $value value <br>";
}
like image 121
Sverri M. Olsen Avatar answered Mar 17 '23 05:03

Sverri M. Olsen