Skip to content

Instantly share code, notes, and snippets.

@royteusink
Created September 26, 2022 10:40
Show Gist options
  • Save royteusink/18bdcb86114dfe0c9531d76476f59f43 to your computer and use it in GitHub Desktop.
Save royteusink/18bdcb86114dfe0c9531d76476f59f43 to your computer and use it in GitHub Desktop.
Search for a key in a nested array
<?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