


Here’s our for loop, made into a simple foreach. Rather than going through an abstract sequence you iterate over a pre-set thing. I’ve always found PHP foreach loops much simpler to understand. If you’ve never seen this syntax before though, it’s a lot to wrap your head around.
#Foreach php optmize code#
What’s great about this code is that if you’ve seen a for loop before (with its weird three-clause syntax of “start condition”, “continue condition”, “per loop operation”), this reads quite simply. You’ll probably use a for loop, like this: for ($x = 1 $x " Let’s say you want a segment of code to run 20 times. The execution speed is very clear from the image below, each variant is sorted according to the speed of execution, the first is the fastest: Below is a code by which you can evaluate the performance of php foreach loop on your server. In PHP, you’ll use a for loop mostly when you want to iterate through a set of numbers. We will first look at how the foreach() function works on an indexed array. We will learn in turn how the PHP foreach function works on both these types of arrays. But before we get too deep on the foreach loop I do think there’s value in covering how these two popular things differ. As we learned in the Syntax of PHP foreach() section above, the foreach function can work on both indexed and associative arrays. PHP improves on the for loop with the foreach loop. Anyone who’s programmed much in any language has heard of a for loop.
