1

I want check my array value with in_array my arrays this is:

multidimensional php arrays

I use this code but it's not work

 if(in_array(167, $array) AND in_array(556, $array)  ) {

 echo 'ok';
 return; 
}

now how can check my values?

saber
  • 306
  • 5
  • 14

5 Answers5

2

in_array() does not work for multi-dimensional arrays , you either have to loop it and do the in_array() check or merge the array into a single one and then do single in_array() check.

Way 1:

foreach($array as $k=>$arr)
{
 if(in_array(167,$arr))
 {
   echo "Found";
 }
}

Way 2: (Merge)

$merged_arr = call_user_func_array('array_merge', $array);
 if(in_array(167,$merged_arr))
 {
   echo "Found";
 }

EDIT :

<?php

$array = array(array(167),array(167),array(556));
$merged_arr = call_user_func_array('array_merge', $array);
$needle_array = array(167,556,223);

foreach($needle_array as $v)
{
    if(in_array($v,$merged_arr))
    {
        echo "Found";
    }
}

You can even use array_intersect() on these two arrays to get the matched content , if that is what you are looking for.

Shankar Damodaran
  • 65,155
  • 42
  • 87
  • 120
1

You could create a mult-dimensional in_array function:

function inArrayMulti($needle, $haystack, $strict=false) {
    foreach( $haystack as $item ) {
        if( is_array($item) ) return inArrayMulti($needle, $item);
        else {
            if( $strict && $needle === $item) ) return true;
            else if( $needle == $item ) return true;
        }
    }

    return false;
}
Cully
  • 4,915
  • 2
  • 23
  • 39
0
May be useful this

return 0 < count(
    array_filter(
        $my_array,
        function ($a) {
            return array_key_exists('id', $a) && $a['id'] == 152;
        }
    )
);

Or

$lookup_array=array();

foreach($my_array as $arr){
    $lookup_array[$arr['id']]=1;
}
Now you can check for an existing id very fast, for example:

echo (isset($lookup_array[152]))?'yes':'no';
dev4092
  • 2,282
  • 1
  • 13
  • 14
0

Loop through the array

<?php
    foreach($array as $ar){
        if(in_array(167,$ar) && in_array(556,$ar)){
            echo "ok";
        }
    }
?>
ksealey
  • 1,446
  • 1
  • 14
  • 14
0

Why all answers use in_array and other difficult construction? We need found only two numbers, easy way for this:

$array = array(array(165), array(167),array(167),array(556));

foreach($array as $key){
    foreach($key as $next){

    echo 167 == $next || 556 == $next ? '<p>Found<p></br>' : '';

    }

}
Brotheryura
  • 1,100
  • 12
  • 20