3v4l.org

run code in 500+ PHP versions simultaneously
<?php $array = array ( 0 => array ( 'id' => '1', 'p_pag' => '0', 'link' => 'Contact', 'children' => array ( 0 => array ( 'id' => '2', 'p_pag' => '1', 'link' => 'Contact-County', 'children' => array ( 0 => array ( 'id' => '3', 'p_pag' => '2', 'link' => 'Contact-Town-1', 'children' => array ( ), ), ), ), ), ), ); function getLinkPathById(array $array, string $toId): ?string { foreach ($array as $row) { if ( $row['id'] === $toId || ($deeper = getLinkPathById($row['children'], $toId)) ) { return '/' . $row['link'] . ($deeper ?? null); } } return null; } echo "1: " . getLinkPathById($array, 1) . PHP_EOL; echo "2: " . getLinkPathById($array, 2) . PHP_EOL; echo "3: " . getLinkPathById($array, 3) . PHP_EOL; echo "4: " . getLinkPathById($array, 4);
Output for 7.4.0 - 7.4.33, 8.0.1 - 8.0.30, 8.1.0 - 8.1.34, 8.2.0 - 8.2.30, 8.3.0 - 8.3.30, 8.4.1 - 8.4.21, 8.5.0 - 8.5.6
1: /Contact 2: /Contact/Contact-County 3: /Contact/Contact-County/Contact-Town-1 4:

preferences:
102.22 ms | 1259 KiB | 4 Q