Tell me more ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

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", $a)) 
{
    echo "Got Irix";
}

//print_r($a);

but what about an multidimensional array (below) - how can I check that value whether it exists in the multi-array?

$b = array(array("Mac", "NT"), array("Irix", "Linux"));

print_r($b);

or I shouldn't be using in_array() when comes to the multidimensional array?

share|improve this question

7 Answers

up vote 70 down vote accepted

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';
share|improve this answer
thank you. the function is elegant! love it! thanks. how can i know it returns true or false as my screen doest show anything when I run your function? thanks. – lauthiamkok Nov 8 '10 at 22:00
@lauthiamkok: Check out my updated usage example ;) – elusive Nov 8 '10 at 22:01
got it! thanks so much! :-))) – lauthiamkok Nov 8 '10 at 22:11
@lauthiamkok: You're welcome! – elusive Nov 8 '10 at 22:15
FYI: in_array_r is data type aware. ex: phpfiddle.org/main/code/at1-qwy – a coder Oct 23 '12 at 15:38
show 4 more comments

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;
}
share|improve this answer
@elusive's function worked out of the box with PHP 5.3.3. – a coder Oct 23 '12 at 15:29

This will do it:

foreach($b as $value)
{
    if(in_array("Irix", $value))
    {
        echo "Got Irix";
    }
}

in_array only operates on a one dimensional array, so you need to loop over each sub array and run in_array on each.

As others have noted, this will only for for a 2-dimensional array. If you have more nested arrays, a recursive version would be better. See the other answers for examples of that.

share|improve this answer
3  
However, this will only work in one dimension. You'll have to create a recursive function in order to check each depth. – metrobalderas Nov 8 '10 at 21:44
i ran the code but it has an error - Parse error: parse error in C:\wamp\www\000_TEST\php\php.in_array\index.php on line 21 - which is if(in_array("Irix", $value) thanks. – lauthiamkok Nov 8 '10 at 21:51
@lauthiamkok: There is a ) missing at the end of the mentioned line. – elusive Nov 8 '10 at 21:52
Thanks, I fixed my answer. That's what happens when I type too fast and don't reread my code. – Alan Geleynse Nov 8 '10 at 21:53
lol i missed that too! thanks! – lauthiamkok Nov 8 '10 at 21:55

if your array like this

$array = array(
              array("name" => "Robert", "Age" => "22", "Place" => "TN"), 
              array("name" => "Henry", "Age" => "21", "Place" => "TVL")
         );

Use this

function in_multiarray($elem, $array,$field)
{
    $top = sizeof($array) - 1;
    $bottom = 0;
    while($bottom <= $top)
    {
        if($array[$bottom][$field] == $elem)
            return true;
        else 
            if(is_array($array[$bottom][$field]))
                if(in_multiarray($elem, ($array[$bottom][$field])))
                    return true;

        $bottom++;
    }        
    return false;
}

example : echo in_multiarray("22", $array,"Age");

share|improve this answer

Please try:

in_array("irix",array_keys($b))
in_array("Linux",array_keys($b["irix"])

Im not sure about the need, but this might work for your requirement

share|improve this answer
1  
How would searching the array keys do anything? $b's array keys are just integers... there are no specified keys in these arrays... and array_keys($b["irix"]) will just throw an error, because $b["irix"] doesn't exist. – Ben D Sep 22 '12 at 19:52

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;
    }
?>
share|improve this answer
elusive's solution is better since it's just for arrays – Gazillion Nov 8 '10 at 21:46

It works too creating first a new unidimensional Array from the original one.

$arr = array("key1"=>"value1","key2"=>"value2","key3"=>"value3");

foreach ($arr as $row)  $vector[] = $row['key1'];

in_array($needle,$vector);
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.