Detecting cyclic arrays in PHP is notoriously difficult to do correctly in pure PHP. This post presents a practical solution using PHP's built-in `count()` function with the `COUNT_RECURSIVE` mode, which emits an `E_WARNING` when it encounters a cyclic array. By setting up a custom error handler to trap that warning, a correct and performant `is_cyclic()` function can be built. The approach is benchmarked as faster than pure PHP alternatives and handles edge cases that break naive implementations. Limitations include no equivalent for detecting cycles in objects, and a note that PHP version upgrades (e.g., PHP 8 converting warnings to exceptions) may require minor adjustments.
Table of contents
Did you know?We can do betterDoes this really work?Does it also work for objects?Wrapping upCodeSort: