How does PHP 'foreach' actually work?

How does PHP 'foreach' actually work?

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

Stefan Bogdanescu

Founder & Senior Architect

How PHP foreach Actually Works

It is a common misconception that foreach simply iterates over a shallow copy of an array. While it is true that modifying the array's contents or structure during iteration often does not affect the loop, the underlying mechanics are more nuanced than "iterating on a snapshot." The behavior stems from a specific interaction between an internal iterator state and the source array pointer, creating a hybrid execution model that can lead to subtle bugs if misunderstood.

When you execute foreach ($array as $item), PHP does not create a full duplicate of your data structure. Instead, it initializes an internal state machine for the loop. Crucially, before the first iteration begins, this internal iterator resets the source array's pointer to the beginning. This is explicitly documented in the manual: "When foreach first starts executing, the internal array pointer is automatically reset to the first element of the array."

This pointer manipulation explains why appending items to an array inside a foreach loop does not trigger an infinite loop. In Test Case 1, where $array[] = $item is executed, the loop continues for exactly five iterations. If PHP were relying solely on the source array pointer to determine termination, adding elements would shift the end marker, causing the loop to chase its own tail forever. Since it doesn't, the loop relies on a pre-calculated count or a snapshot of the original key range.

However, the relationship between the internal iterator and the source array is not entirely severed. The source array's pointer is modified by the foreach construct itself; after the loop finishes, the internal pointer for that specific array instance will sit at the end. This distinction becomes critical when mixing foreach with functions like each(), reset(), or direct pointer manipulation.

Consider a scenario where you attempt to use each($array) inside a foreach loop. In Test Case 4, calling each($array) does not break the iteration. However, this is because foreach manages its own internal cursor logic independently of external pointer changes made during execution. The loop continues based on its internal state, ignoring that the source pointer might have been nudged by each().

The real danger lies in modifying the array's keys or structure in ways that conflict with the pre-calculated iteration range. While appending values (pushing) is generally safe because the count is fixed at the start, inserting elements or unsetting keys can lead to unexpected behavior depending on how the internal iterator handles skipped indices.

There is a specific edge case where using pointer-altering functions inside foreach causes issues: when modifying the array such that the internal loop logic diverges from the actual data present. While simple appends are safe, relying on the "copy" theory can be dangerous if you assume that any modification is isolated. The manual warns that altering the array during iteration may lead to unexpected behavior because foreach relies on the internal pointer changing. If your code explicitly manipulates the source array pointer (e.g., via each() or reset()) in a way that conflicts with the internal iterator's expectations, you risk skipping elements or entering inconsistent states.

For developers working within the Laravel ecosystem, this behavior is rarely an issue because framework collections and Eloquent query results often return new instances when modified, effectively isolating the iteration context. However, when dealing with raw arrays passed between methods or stored in sessions, understanding that foreach uses a mix of internal state and source pointer resets is vital for preventing infinite loops or skipped data points.

Our network