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.


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: