I use in_array()
to check whether a value exists in an array like below,
$a = array(\"Mac\", \"NT\", \"Irix\", \"Linux\");
if (in_array(\"Irix\"
This is the first function of this type that I found in the php manual for in_array. Functions in the comment sections aren't always the best but if it doesn't do the trick you can look in there too :)
<?php
function in_multiarray($elem, $array)
{
// if the $array is an array or is an object
if( is_array( $array ) || is_object( $array ) )
{
// if $elem is in $array object
if( is_object( $array ) )
{
$temp_array = get_object_vars( $array );
if( in_array( $elem, $temp_array ) )
return TRUE;
}
// if $elem is in $array return true
if( is_array( $array ) && in_array( $elem, $array ) )
return TRUE;
// if $elem isn't in $array, then check foreach element
foreach( $array as $array_element )
{
// if $array_element is an array or is an object call the in_multiarray function to this element
// if in_multiarray returns TRUE, than return is in array, else check next element
if( ( is_array( $array_element ) || is_object( $array_element ) ) && $this->in_multiarray( $elem, $array_element ) )
{
return TRUE;
exit;
}
}
}
// if isn't in array return FALSE
return FALSE;
}
?>
what about array_search? seems it quite faster than foreach according to https://gist.github.com/Ocramius/1290076 ..
if( array_search("Irix", $a) === true)
{
echo "Got Irix";
}
in_array()
does not work on multidimensional arrays. You could write a recursive function to do that for you:
function in_array_r($needle, $haystack, $strict = false) {
foreach ($haystack as $item) {
if (($strict ? $item === $needle : $item == $needle) || (is_array($item) && in_array_r($needle, $item, $strict))) {
return true;
}
}
return false;
}
Usage:
$b = array(array("Mac", "NT"), array("Irix", "Linux"));
echo in_array_r("Irix", $b) ? 'found' : 'not found';
Great function, but it didnt work for me until i added the if($found) { break; }
to the elseif
function in_array_r($needle, $haystack) {
$found = false;
foreach ($haystack as $item) {
if ($item === $needle) {
$found = true;
break;
} elseif (is_array($item)) {
$found = in_array_r($needle, $item);
if($found) {
break;
}
}
}
return $found;
}