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?

7
  • 1
    why not: var_dump(in_array(2, $a) && in_array(5, $a)) Commented Jun 5, 2014 at 9:30
  • that wont take the orders into account. Would be true for 2,5 and 5,2 Commented Jun 5, 2014 at 9: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')) Commented Jun 5, 2014 at 9:39
  • in_array won't do it. It's simply not in the scope of what it does. You'll have to loop yourself. Commented Jun 5, 2014 at 9:41
  • this function might get you started Commented Jun 5, 2014 at 9:47

2 Answers 2

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
Sign up to request clarification or add additional context in comments.

Comments

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)) ...

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.