What is the best way to check if an array is recursive in PHP ?
Given the following code:
I've dug into this in depth some time ago, and I was unable to find any useful mechanism for detecting recursion in PHP arrays.
The question boils down to whether it's possible to tell whether two PHP variables are references to the same thing.
If you're working with objects rather than arrays (or even objects within your arrays), then it is possible, as one can find out whether two objects are the same reference using spl_object_hash()
. So if you have objects in your structure, then you can detect recursion by traversing up the tree and comparing the objects.
However for regular variables -- ie non-objects -- it isn't possible to detect this easily using standard PHP.
The work arounds are to use print_r()
(as you already know) or var_dump()
, but neither of these are particularly elegant solutions.
There is also a function provided by xDebug which can help, xdebug_debug_zval()
, but that's obviously only available if you've got xDebug installed, which isn't recommended on a production system.
Further advice and suggestions available here.