$array = [
385 => 392,
386 => 392,
387 => 392,
390 => 402,
402 => 421,
405 => 401,
409 => 416,
410 => 401,
414 => 402,
416 => 389,
420 => 421,
421 => 422,
422 => 420,
];
foreach ($array as $key => $value) {
$level=0;
$leaf=[$key=>$level]; $v=$value;
while(true){
if(!isset($array[$v])) break;
$v=$array[$v];
if(isset($leaf[$v])) {
// loop found
// is it real loop ?
if($key==$v) {
printf("\n %s => %s", $key, $value);
}
break;
}
$leaf[$v]=++$level;
}
}