Created
September 26, 2022 10:40
-
-
Save royteusink/18bdcb86114dfe0c9531d76476f59f43 to your computer and use it in GitHub Desktop.
Search for a key in a nested array
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
function searchByKey(array $array, $key) | |
{ | |
if (array_key_exists($key, $array)) return $array[$key]; | |
$recursive = function($chunk) use ($key, &$recursive) { | |
foreach ($chunk as $k => $v) { | |
if ($k === $key) return $chunk[$key]; | |
if (is_array($v) && $found = $recursive($v)) return $found; | |
} | |
return null; | |
}; | |
return $recursive($array); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment