PHP for loop vs. foreach with range

PHP for loop vs. foreach with range

  1. Blog
  2. 15 November 2026
  3. 3 min read

Stefan Bogdanescu

Founder & Senior Architect

PHP for loop vs. foreach with range

Benchmarks in PHP often yield surprising results that defy initial intuition. A common pattern involves iterating through a sequence of numbers to perform bulk operations, such as seeding a database or processing a list of IDs. Developers frequently reach for range() combined with foreach because the syntax is concise and readable. However, performance profiles reveal a significant disparity between this approach and a standard numeric for loop.

When benchmarking a simple iteration from 0 to 10,000, the foreach(range(0, 10000)) pattern takes approximately 3.847 ms. In contrast, a traditional for loop completes the same task in roughly 0.663 ms. That is nearly a six-fold difference in execution time. While micro-optimizations often fall into the trap of premature optimization, understanding the underlying mechanics of how PHP constructs these loops is vital for writing efficient code at scale.

The performance gap stems from how range() and foreach handle memory and iteration logic. The range() function generates a complete array in memory before the loop ever begins. For a range of 10,000 integers, this involves allocating contiguous memory blocks, populating every index with an integer value, and calculating the total hash table size for that specific array structure. Even though modern PHP engines use optimized internal array representations (like IS_ARRAY), creating that intermediate object adds overhead before a single iteration occurs. Furthermore, foreach iterates over this pre-built array by maintaining an internal pointer and accessing each element sequentially.

Conversely, a for loop with a numeric condition operates differently. It does not require constructing an intermediate array object. The loop variable $i is simply incremented in place within the execution context. This approach avoids the memory allocation cost of creating the array entirely. While foreach(range(...)) might be slightly more readable for some, the for loop offers a direct path to iteration without the hidden cost of materializing the entire dataset into memory first.

In scenarios where you are iterating over a large range of numbers purely for counting or sequential access, the for loop is technically superior. The trade-off lies in code clarity versus raw speed. If your goal is simply to execute logic 10,000 times, the readability gain from foreach does not justify the performance penalty. However, if you need to map values or work with an associative structure where the keys are generated dynamically, range() becomes necessary.

When working within frameworks like Laravel, this distinction remains relevant. While Laravel abstractions often abstract these low-level loops away, writing raw SQL queries or processing large datasets in PHP still benefits from mindful iteration choices. If you are building a high-performance package or optimizing a legacy script, sticking to numeric for loops for simple ranges is the pragmatic choice.

It is also worth noting that PHP 8 introduced significant performance improvements regarding array handling and JIT compilation in later versions. While these optimizations narrow some gaps, they do not eliminate the fundamental cost of creating a temporary array versus incrementing a variable. The lesson holds: avoid generating unnecessary arrays when you only need a sequence of integers.

For developers focused on scalability, the takeaway is clear. When you see a snippet using foreach(range(...)) in a performance-critical path, consider refactoring it to a numeric loop unless there is a specific reason to use an array structure. The six-fold speedup achieved by skipping the temporary array creation is substantial enough to matter when processing thousands or millions of records.

Our network