Forked from wildlyinaccurate/recursive_array_search.php
Created
August 10, 2016 15:47
-
-
Save jasondavis/3df8ce07cf244afe2f3936ca8d1219dc to your computer and use it in GitHub Desktop.
PHP Recursive Array Search
This file contains hidden or 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