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.
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>";
}
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With