Domain Empire

[PHP] In_array for multidimensional arrays

Spaceship Spaceship
Watch
Simple function to check if a value exists in a multidimensional array.

PHP:
function multi_in_array($value, $array)
{
	foreach ($array AS $item)
	{
		if (!is_array($item))
		{
			if ($item == $value)
			{
				return true;
			}
			continue;
		}

		if (in_array($value, $item))
		{
			return true;
		}
		else if (multi_in_array($value, $item))
		{
			return true;
		}
	}
	return false;
}

// Example
$array = array(
	'Test' => array('test1', 'test2', 'test3'),
	'Hmm'  => array('hmm1', 'hmm2', 'hmm3')
);

var_dump(multi_in_array('test2', $array));
var_dump(multi_in_array('hmm1', $array));
var_dump(multi_in_array('alsdkfj', $array));

// bool(true) bool(true) bool(false)
 
0
•••
The views expressed on this page by users and staff are their own, not those of NamePros.
Thanks Eric :)

I'd leave rep for you, but i can't :P

Nothing but quality snippets from you :P
 
0
•••
good function similar one avilable in php.net
 
0
•••
  • The sidebar remains visible by scrolling at a speed relative to the page’s height.
Back