What is the best way to check if an array is recursive in PHP ?
Given the following code:
<?php
$myarray = array('test',123);
$myarray[] = &$myarray;
print_r($myarray);
?>
From the PHP Manual:
The print_r() will display RECURSION when it gets to the third
element of the array.There doesn’t appear to be any other way to scan an array for
recursive references, so if you need to check for them, you’ll have to
use print_r() with its second parameter to capture the output and look
for the word RECURSION.
Is there more elegant way of checking ?
PS. This is how I check and get the recursive array keys using regex and print_r()
$pattern = '/\n \[(\w+)\] => Array\s+\*RECURSION\*/';
preg_match_all($pattern, print_r($value, TRUE), $matches);
$recursiveKeys = array_unique($matches[1]);
Thanks
It’s always fun to try solving “impossible” problems!
Here’s a function that will detect recursive arrays if the recursion happens at the top level:
See it in action.
Detecting recursion at any level would obviously be more tricky, but I think we can agree that it seems doable.
Update
And here is the recursive (pun not intended but enjoyable nonetheless) solution that detects recursion at any level:
See it in action.
Of course this can also be written to work with iteration instead of recursion by keeping a stack manually, which would help in cases where a very large recursion level is a problem.