Find the secrets to infinite income, and automate it!
22 Jul
I needed a recursive in_array function the other day and disliked all the samples I found on php.net. I wrote this one using the StandardPHPLibrary. It will recursively search through a multidimensional array and return true if the $needle is found in the $haystack.
function in_array_recursive($needle, $haystack) { $it = new RecursiveIteratorIterator(new RecursiveArrayIterator($haystack)); foreach($it AS $element) { if($element == $needle) { return true; } } return false; }
One Response for "Recursive PHP in_array function"
you used the built in iterator very impressive
here is another
function array_search_recursive( $needle, $haystack ) {
$path = NULL;
$keys = array_keys($haystack);
while (!$path && (list($toss,$k)=each($keys))) {
$v = $haystack[$k];
if (is_scalar($v)) {
if ($v===$needle) {
$path = array($k);
}
} elseif (is_array($v)) {
if ($path=array_search_recursive( $needle, $v )) {
array_unshift($path,$k);
}
}
}
return $path;
}
Leave a reply