If you are looking to do a recursive array search in PHP (and don’t feel like writing your own), you might have tried a number of the functions described in the comments section of the array_search page in the manual. Just for future reference, I have tried a few, but not all of them worked for me. This one did:
/** * Searches haystack for needle and * returns an array of the key path if * it is found in the (multidimensional) * array, FALSE otherwise. * * @mixed array_searchRecursive ( mixed needle, * array haystack [, bool strict[, array path]] ) */ function array_searchRecursive( $needle, $haystack, $strict=false, $path=array() ) { if( !is_array($haystack) ) { return false; } foreach( $haystack as $key => $val ) { if( is_array($val) && $subPath = array_searchRecursive($needle, $val, $strict, $path) ) { $path = array_merge($path, array($key), $subPath); return $path; } elseif( (!$strict && $val == $needle) || ($strict && $val === $needle) ) { $path[] = $key; return $path; } } return false; }
The comment directly following it (above it, actually) describes a modified version that would let you restrict your search by key.
6 Comments
Well this does exactly what I need. Saved me a lot of time, thanks!
Thanks, works great! You might want to replace the > and &’s to normal characters.
Was exactly what I needed, thanks!
This is a copy of the php.net manual user contributions.
However it does not perform correctly.
What if an occurrence of the needle is found in the array more than once ?
Thank you! I also couldn’t get the examples on php.net to work in my script. This worked almost immediately!
well this is not what i was searching for , but it surely helped me think of the logic to make my own function for a certain process :) Thanks a lot .
Post a Comment