Fix Recursion Detected Errors in Nested PHP Arrays

Last updated: November 30, 2026.

A nested PHP array can contain a reference back to an ancestor. Recursive array functions can then fail with “Recursion detected”. If the structure is meant for walking, merging or export, keep back links as IDs.

<?php

$settings = [
    'site' => [
        'id' => 'site',
        'sections' => [
            ['id' => 'catalog', 'parent_id' => 'site'],
        ],
    ],
];

$ids = [];
array_walk_recursive($settings, static function ($value, $key) use (&$ids): void {
    if ($key === 'id') {
        $ids[] = $value;
    }
});

echo implode(', ', $ids), PHP_EOL; // site, catalog

Find where the back reference is created

Search the code that builds the structure for assignments by reference. Pay particular attention to code that attaches a parent to a child after it has already attached the child to the parent. That can create a cycle in an otherwise small structure. Reusing a reference to a structure elsewhere does not by itself imply that a path leads back to an ancestor.

The example retains the parent relationship as parent_id. A recursive walk sees that value as a string. Code that needs to look up the parent can use a separate ID index. If your application intentionally models a graph, use a traversal that remembers visited nodes rather than feeding the graph to a tree walker.

Build a fresh array before processing it

When preparing config or export data, construct a new array from known fields. A plain assignment is insufficient for stripping embedded references, because existing reference relationships inside PHP arrays can survive a copy. For a known back-link field, omit it from the export and write its ID instead.

When a recursive processing step fails, rebuild the structure and repeat it from the start. A walk that mutates values may have changed earlier leaves before reaching a cycle. Test the exported shape and the result of walking or merging it, including any relationship that previously pointed up the tree.

Documentation

Related guides

Sergey Kornilov

Sergey Kornilov