Infinite Recursion

<?php

$a = [1,2,3];
$a[] = &$a;

print_r($a);

function foo($a) {
    foreach($a as $b) {
        if (is_array($b)) {
            foo($b);
        } else {
            print $b.PHP_EOL;
        }
    }
}

// Infinite call
//foo($a);

Recursive functions must be protected against infinite recursion: the kind of loop that never stops.

In this particular case, injecting a reference onto the array itself is a valid PHP syntax. When in the loop, it is detected as an array, and starts again the call. This never stops.

The recursive function must be protected with a nesting level, to avoid such cases.

Native functions, such as print_r() and var_dump() have been protected since PHP 7, at least.

The same problem may be created with an object, and a link to itself, although they are less prone to be used in recursive loop, unlike arrays.

See Also

PHP Features

Last updated: 10 August 2026