Skip to content

Instantly share code, notes, and snippets.

@wildlyinaccurate
Created April 23, 2012 21:39
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save wildlyinaccurate/2474033 to your computer and use it in GitHub Desktop.
Save wildlyinaccurate/2474033 to your computer and use it in GitHub Desktop.
PHP Recursive Array Search
<?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 <joseph@wildlyinaccurate.com>
*/
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