$arr = array(
'a' => 1,
'b' => 15,
'c' => 0,
);
$arr['c'] = &$arr;
print_r($arr); // <-- CYCLE
Do you know how can I detect if I have array values that somehow point to the existing element, or cause a infinite loop?
Use memory
, Luke. When your iterator comes across the array as an elementof another one, just store reference/id of it to smth like set or list (or another suitable container, eg. array). So you memorize what array you have already processed, and then ignore it when meet next time or stop the loop.PS: I’m using spl_object_hash as a ID-function, you may use another one, if prefered (but i don’t know others that can identify the same objects, as this one does).
UPD: Using
spl_object_hashdoesn’t give right results as of PHP 5.3.10: it treats any array as the same object regardless of its content. But using smth like%hash_fn%(serialize($array))works well (beware of performance degradation!).