Forked from paulhhowells/recursively to find the first instance of a key and return its value.php
Last active
August 29, 2015 14:15
-
-
Save baerkins/2d78e0f65739cff5df94 to your computer and use it in GitHub Desktop.
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