Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save paulhhowells/5389654 to your computer and use it in GitHub Desktop.
Save paulhhowells/5389654 to your computer and use it in GitHub Desktop.
PHP: search an array recursively to find the first instance of a key and return its value. array_find_first_recursive($needle, $haystack)
/*
* search an array recursively to find
* the first instance of a key and return its value
*
* useful when you do not know the location of a key nested (only once) in a multidimensional array
*
*/
function array_find_first_recursive($needle_key, array $haystack) {
if (array_key_exists($needle_key, $haystack)) {
return $haystack[$needle_key];
}
foreach ($haystack as $key => $value) {
if (is_array($value)) {
$result = array_find_first_recursive($needle_key, $value);
if ($result) {
return $result;
}
}
}
return false;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment