Detecting cyclic (recursive) arrays in pure PHP is fundamentally impossible due to how PHP handles value assignments of arrays containing references. The post walks through a naive marker-based detection algorithm, then demonstrates how a specially crafted array returned from a function causes infinite recursion. The root cause lies in two PHP behaviors: reference aliasing during array value assignment is runtime-dependent, and actual array copying is deferred until mutation (copy-on-write). When the algorithm tries to mark an array, PHP creates a new copy instead of modifying the original, causing the cycle to grow infinitely deeper. The takeaway is to avoid copying arrays that contain aliases, as the PHP Language Specification itself warns this behavior is implementation-defined.

10m read timeFrom hbgl.dev
Post cover image
Table of contents
Attempting a pure PHP solutionBreaking the pure PHP solutionWhat is going on inside the arrayArrays cannot be trustedThe morale of this storyWrapping up

Sort: