Last active
December 16, 2015 06:09
-
-
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)
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
/* | |
* 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