Created
December 12, 2012 00:34
-
-
Save rianrainey/4263778 to your computer and use it in GitHub Desktop.
PHP doesn't make it very easy to recursively look inside a multi-dimensional array. These couple methods make that easier.
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
$simpsons = array('bart', 'lisa', 'homer'); | |
echo in_array_r("bart", $simpsons) ? 'found' : 'not found'; |
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
/** | |
* Recursively look for Needle in Haystack | |
* @param $needle | |
* @param $haystack | |
* @returns boolean | |
*/ | |
function in_array_r($needle, $haystack, $strict = true) { | |
foreach ($haystack as $item) { | |
if (($strict ? $item === $needle : $item == $needle) || (is_array($item) && in_array_r($needle, $item, $strict))) { | |
return true; | |
} | |
} | |
return false; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment