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?

1

5 Answers 5

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.

Sign up to request clarification or add additional context in comments.

1 Comment

I want check two value 167 and 556 when check two value not work
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;
}

1 Comment

There was a small bug in my original version. Made a small change and it works now.
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';

Comments

0

Loop through the array

<?php
    foreach($array as $ar){
        if(in_array(167,$ar) && in_array(556,$ar)){
            echo "ok";
        }
    }
?>

Comments

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>' : '';

    }

}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.