PHP’s Foreach is the Fastest

1977 Yamaha RD400

1977 Yamaha RD400

I have always assumed that using PHP’s foreach loop was the easiest, but not the fastest way to loop through an array. I also assumed that the PHP *array_** functions were the preferred method, as the PHP developers would be able to do some super-efficient magic to make these function super fast.

Apparently, I was wrong.

For me, when looping, I almost exclusively use foreach loops, but only because I think they’re the easiest and more readable loop in PHP. But I often use the *array_** functions thinking there’s a performance improvement for doing so. But now it turns out that the foreach loop is actually the fastest way to process and array.

In a blog post, the writer ran some speed tests on the various looping methods and array_** functions. The *foreach loop performed better than every looping method or array_** function. The *while loop is pretty close in terms of performance, and there are instances when it makes sense. I haven’t felt the need to use a for loop in years, which is the slowest, but that seems obvious.

There’s still obviously a use for the array_* functions, but quick and dirty stuff, the foreach loop is the way to go.

Interesting stuff, it’s always a good idea to test ones assumptions from time-to-time. What was the best way to write PHP in 1997, is very different today.

Share Button