Loops can save a lot of redundancy in your code by performing a particular task over and over again. However, to keep the loop as efficient as possible, here are some tips to follow. Note that these tips apply to many programming languages, not just PHP but examples are given in PHP code.

1) Avoid nested loops if possible.

Nesting loops is sometimes necessary but if possible, it’s best to avoid them. Each nested loop exponentially increases the number of iterations required.2) Avoid functions in loop heads
Here is a very common inefficiency that I see. It goes something like this:

for ($i=0; $i<count($myarray); $i++) {
   //do something
}

using the count() function in the header of your loop requires the array to be counted every interaction. Instead, do the count once, store it in a variable and use that instead!

$numelements = count($myarray);
for ($i=0; $i<$numelements; $i++) {
   //do something
}


3) Don’t go through the same loop twice

If you’re pulling data from an array and displaying it in two places on your page, there is no need to go through the loop twice! Simply save that data into a variable the first time around and call that variable the second time.

If your application is relatively simple you probably won’t notice any difference at all after applying these tips. Sometimes I feel we’re spoiled by the sheer amount of computing power we have available to us that we don’t care about coding efficiently. When I do statistical programming (looping over millions of elements), these simple tips actually do help shave minutes off running time!

Popularity: 2% [?]

Leave a Reply