What is the best way to check if an array is recursive in PHP ?
Given the following code:
The following function is simpler[opinion] than the code in the accepted answer, and seems to work for any use case that I have been able to contrive. It also seems to be surprisingly fast, typically taking microseconds, though I have not done extensive benchmarking. If there is a problem with it, I would be grateful if somebody could point it out?
// returns TRUE iff the passed object or array contains
// a self-referencing object or array
function is_r($obj, &$visited=array())
{
$visited[] = $obj;
foreach ($obj as $el)
{
if (is_object($el) || is_array($el))
{
if (in_array($el, $visited, TRUE))
return TRUE;
if (is_r($el, $visited))
return TRUE;
}
}
return FALSE;
}