What are some alternative approaches to detecting recursion in PHP objects and arrays aside from var_dump() and print_r()?

When dealing with complex PHP objects or arrays that may contain recursive references, it can be challenging to detect them using traditional methods like var_dump() or print_r(). One alternative approach is to use a custom function that keeps track of visited objects or arrays to identify recursion.

function detectRecursion($var, $visited = array()) {
    if (is_object($var) || is_array($var)) {
        if (in_array($var, $visited, true)) {
            return 'Recursion detected';
        }
        $visited[] = $var;
        foreach ($var as $key => $value) {
            detectRecursion($value, $visited);
        }
    }
}

// Example usage
$recursiveArray = [];
$recursiveArray['self'] = &$recursiveArray;
detectRecursion($recursiveArray);