WP-Mix

A fresh mix of code snippets and tutorials

PHP Search Multidimensional Array

When you need to search an array using PHP, you can call upon the ancient powers of in_array() and call it a day. But that only works for flat, or one-dimensional arrays. What if you need to find a value in a multi-dimensional array? Well my friend, there isn’t a native PHP function to help you there.. but I do have a solution..

function shapeSpace_search_array($needle, $haystack) {
	
	if (in_array($needle, $haystack)) {
		return true;
	}
	
	foreach ($haystack as $item) {
		if (is_array($item) && array_search($needle, $item)) 
		return true;
	}
	
	return false;
	
}

This function returns true if the specified value ($needle) is found within the specified array ($haystack), or false if the value is not found in the array. Works on any array, flat/one-dimensional arrays and multidimensional arrays. Doesn’t even matter.

Usage

Works just like in_array():

if (shapeSpace_search_array($value, $array)) {
	echo 'Yep, the $value was found in the $array';
}

Now go forth and find all the things in your multidimensional arrays ;)

★ Pro Tip:

USP ProSAC Pro