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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
<?php function multidimensional_array_search($search_value,$array) { $mached = array(); if(is_array($array) && count($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 :
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
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; } |
I hope you like this Post, Please feel free to comment below, your suggestion and problems if you face - we are here to solve your problems.
I am Arjun from Hyderabad (India). I have been working as a software engineer from the last 7+ years, and it is my passion to learn new things and implement them as a practice. Aside from work, I like gardening and spending time with pets.
array given is not a multidimensional array