Posts Tagged ‘while vs foreach’

while vs foreach in PHP

There can be a lot many ways to get a specific task done. To display a certain number of items form an array, we have two ways. One is to use while() statement and the other one to use foreach() statement. The syntax for both are as follows :
while (list($key, $value) = each($pagearray)){
echo “Key: $key; Value: $value”;
}
foreach ($pagearray as $key => $value){
echo “Key: $key; Value: $value”;
}

Though for smaller arrays, the one containing a limited number of elements, both can be used. But from the optimisation point of view, the use of foreach() is suggested. foreach() is optimised for iteration over collections. Or in other words, this statement works faster than while(). This is more efficient as for every loop, we need to make a call to two functions every single time and so this makes while() inefficient.