0

I want to do the following:

$a = array();
$a[] = array(1,2);
$a[] = array(2,5);
$a[] = array(3,4);
var_dump (in_array(array(2,5), $a));

this returns OK, as it expected, but if the source array is not fully matched:

$a = array();
$a[] = array(1,2, 'f' => array());
$a[] = array(2,5, 'f' => array());
$a[] = array(3,4, 'f' => array());
var_dump (in_array(array(2,5), $a));

it returns false. Is there a way to do it with the built-in way, or I have to code it?

John Smith
  • 6,687
  • 12
  • 62
  • 112

2 Answers2

2

in_array() is just not the thing that you should use for this issue. Because it will compare values with type casting, if that's needed. Instead, you may use plain loop or something like:

function in_array_array(array $what, array $where)
{
   return count(array_filter($where, function($x) use ($what)
   {
      return $x===$what;
   }))>0;
}

So then

var_dump(in_array_array(array(2, 5), $a)); //true
Alma Do
  • 36,374
  • 9
  • 70
  • 101
1
$needle = array(2, 5);
$found = array_reduce($a, function ($found, array $array) use ($needle) {
    return $found || !array_diff($needle, $array);
});

This does an actual test of whether the needle is a subset of an array.

function subset_in_array(array $needle, array $haystack) {
    return array_reduce($haystack, function ($found, array $array) use ($needle) {
        return $found || !array_diff($needle, $array);
    });
}

if (subset_in_array(array(2, 5), $a)) ...
deceze
  • 491,798
  • 79
  • 706
  • 853