Skip to content

PHP Multidimensional Array Searching

Last updated on October 19, 2014

This post is about Multidimensional Array Searching , there is no builtin function in PHP to search Multidimensional Array, we can write our own function using recursive procedure.

Here is the Simple recursive function to search value in multidimensional array in php.This function returns key of the matched given value if it is in the array.

 0) {
		foreach($array as $key => $value) {
			if(is_array($value) && count($value) > 0) {
				multidimensional_array_search($search_value,$value);
			} else {
				return array_search($search_value,$array); exit;
			}
		}
	}
}

// useage
echo multidimensional_array_search('test3',array('test','test1','test2','test3'));

?>

Another Method :

function recursiveArraySearch($haystack, $needle, $index = null)
{
    $aIt = new RecursiveArrayIterator($haystack);
    $it = new RecursiveIteratorIterator($aIt);
    
    while($it->valid())
    {
        if (((isset($index) AND ($it->key() == $index)) OR (!isset($index))) AND ($it->current() == $needle)) {
            return $aIt->key();
        }
        
        $it->next();
    }
    
    return false;
}
0 0 votes
Article Rating
Subscribe
Notify of
guest

1 Comment
Most Voted
Newest Oldest
Inline Feedbacks
View all comments