1

It's a bit like in_array but while in_array checks the presence of one element in an array and returns true and false accordingly, I want to know whether all elements of array1 is part of array2.

Ex:

$array1 = array(3, 30);
$array2 = array(5, 30);
$array3 = array(5, 50);

$array = array(50,7,8,456,1,5,567);

function new_in_array($array1,$array) // false
function new_in_array($array2,$array) // false
function new_in_array($array3,$array) // true

Any idea?

1
  • Thanks guys. Took @alexn's answer. Cheers. Commented Apr 11, 2011 at 13:08

4 Answers 4

4

array_intersect will do:

<?php
$first = array('foo', 'bar');
$second = array('foo', 'bar','baz');

var_dump(array_intersect($first, $second) === $first); // True

$first = array('foo', 'bar', 'hello');
$second = array('foo', 'bar','baz');

var_dump(array_intersect($first, $second) === $first); // False
Sign up to request clarification or add additional context in comments.

Comments

2

Use array_intersect to intersect those two and check the number of elements in the return array:

$intersect = array_intersect($array1, $array2);
if (count($intersect) == count($array1)) {
   // array1 is fully contained in array2
}

Comments

2

Or use array_diff():

function array_contains($haystack, $needles) {
  return !count(array_diff($needles, $haystack));
}

array_contains($array2, $array1); // all elements of array1 is part of array2?

Comments

0

You could also use a for loop.

for ($i = 0; $i < sizeof($array1); $i++) {
  if (!in_array($array1[$i], $array2)) {
    return False;
  }
}
return True;

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.