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,129
  • 12
  • 68
  • 123
  • 1
    why not: var_dump(in_array(2, $a) && in_array(5, $a)) – ka_lin Jun 05 '14 at 09:30
  • that wont take the orders into account. Would be true for 2,5 and 5,2 – John Smith Jun 05 '14 at 09:37
  • 1
    that will not work at all. First approach checks if there are `array` as element in `$a`, and if it is with values `2, 5`. But separately `2` and `5` are not into `$a` because `$a` is represented as `$a = array(1 = > array(2, 5, 'f'))` – Royal Bg Jun 05 '14 at 09:39
  • `in_array` won't do it. It's simply not in the scope of what it does. You'll have to loop yourself. – deceze Jun 05 '14 at 09:41
  • [this function](http://stackoverflow.com/questions/4128323/in-array-and-multidimensional-array#answer-4128377) might get you started – pulsar Jun 05 '14 at 09:47
  • @verbumSapienti not sure it will work for that particular case – Royal Bg Jun 05 '14 at 09:48
  • @Royal it should with some tweaking – pulsar Jun 05 '14 at 09:51

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
  • 37,009
  • 9
  • 76
  • 105
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
  • 510,633
  • 85
  • 743
  • 889