Created
April 23, 2012 21:39
-
-
Save wildlyinaccurate/2474033 to your computer and use it in GitHub Desktop.
PHP Recursive Array Search
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
<?php | |
/** | |
* Recursively search an array for a given value. Returns the root element key if $needle | |
* is found, or FALSE if $needle cannot be found. | |
* | |
* @param mixed $needle | |
* @param array $haystack | |
* @param bool $strict | |
* @return mixed|bool | |
* @author Joseph Wynn <[email protected]> | |
*/ | |
function recursive_array_search($needle, $haystack, $strict = true) | |
{ | |
$iterator = new RecursiveIteratorIterator(new RecursiveArrayIterator($haystack), RecursiveIteratorIterator::SELF_FIRST); | |
while ($iterator->valid()) | |
{ | |
if ($iterator->getDepth() === 0) | |
{ | |
$current_key = $iterator->key(); | |
} | |
if ($strict && $iterator->current() === $needle) | |
{ | |
return $current_key; | |
} | |
elseif ($iterator->current() == $needle) | |
{ | |
return $current_key; | |
} | |
$iterator->next(); | |
} | |
return false; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment