3v4l.org

run code in 500+ PHP versions simultaneously
<?php $arr = ["categories" => [ [ 'id' => 368, 'name' => 'Aksesuar', 'parentId' => NULL, 'subCategories' => [ [ 'id' => 387, 'name' => 'Saat', 'parentId' => 368, 'subCategories' => [] ], [ 'id' => 394, 'name' => 'Şapka', 'parentId' => 368, 'subCategories' => [] ], [ 'id' => 396, 'name' => 'Takı & Mücevher', 'parentId' => 368, 'subCategories' => [ [ 'id' => 397, 'name' => 'Bileklik', 'parentId' => 396, 'subCategories' => [ [ 'id' => 1238, 'name' => 'Altın Bileklik', 'parentId' => 397, 'subCategories' => [] ] ] ] ] ], ] ] ]]; function recursive(string $needle, array $categories, $id): ?array { foreach ($categories as $cat) { if (array_key_exists($needle, $cat) && $cat[$needle] === $id) { // make sure that if correct category is found, // no subcategories will be included unset($cat['subCategories']); return $cat; } else { $subCat = recursive($needle, $cat['subCategories'], $id); // if the $subCat is not null, it indicates the category // with the correct id, or one of it's parent has been found if ($subCat !== null) { $cat['subCategories'] = $subCat; return $cat; } } } return null; } var_dump(recursive('id', $arr['categories'], 397));
Output for 7.3.0 - 7.3.33, 7.4.0 - 7.4.33, 8.0.0 - 8.0.30, 8.1.0 - 8.1.34, 8.2.0 - 8.2.30, 8.3.0 - 8.3.4, 8.3.6 - 8.3.30, 8.4.1 - 8.4.21, 8.5.0 - 8.5.7
array(4) { ["id"]=> int(368) ["name"]=> string(8) "Aksesuar" ["parentId"]=> NULL ["subCategories"]=> array(4) { ["id"]=> int(396) ["name"]=> string(17) "Takı & Mücevher" ["parentId"]=> int(368) ["subCategories"]=> array(3) { ["id"]=> int(397) ["name"]=> string(8) "Bileklik" ["parentId"]=> int(396) } } }
Output for 8.3.5
Warning: PHP Startup: Unable to load dynamic library 'sodium.so' (tried: /usr/lib/php/8.3.5/modules/sodium.so (libsodium.so.23: cannot open shared object file: No such file or directory), /usr/lib/php/8.3.5/modules/sodium.so.so (/usr/lib/php/8.3.5/modules/sodium.so.so: cannot open shared object file: No such file or directory)) in Unknown on line 0 array(4) { ["id"]=> int(368) ["name"]=> string(8) "Aksesuar" ["parentId"]=> NULL ["subCategories"]=> array(4) { ["id"]=> int(396) ["name"]=> string(17) "Takı & Mücevher" ["parentId"]=> int(368) ["subCategories"]=> array(3) { ["id"]=> int(397) ["name"]=> string(8) "Bileklik" ["parentId"]=> int(396) } } }

preferences:
100.66 ms | 1478 KiB | 4 Q