1

I have two arrays-

$ar = array("a","b","c");
$xy = array("a","b","c","d","e");

I have to find out each element in $ar in $xy. If all elements are in $xy then it should return true.

I used in_array() but it returns true though one element is found.

Any help is appreciated. Thanks.

shanethehat
  • 15,460
  • 11
  • 57
  • 87
SandyK
  • 465
  • 1
  • 9
  • 28
  • possible duplicate of [PHP - Check if two array are equal](http://stackoverflow.com/questions/5678959/php-check-if-two-array-are-equal) – Gordon Jul 22 '11 at 09:15
  • @gordon: That dupe checks for equality which won't work for this question. However a good related one. – hakre Jul 22 '11 at 09:32
  • @hakre there is multiple answers to that question. It contains all the OP needs (and could have found in the manual easily if he had bothered to search). A dupe isnt a dupe just for the accepted answer. – Gordon Jul 22 '11 at 09:34
  • @Gordon: Sure, was just saying. But the premise of the question differs. Find all of one set in another set or compare two sets for equality. – hakre Jul 22 '11 at 09:36
  • possible duplicate of [Does array_a contain all elements of array_b](http://stackoverflow.com/questions/4945049/does-array-a-contain-all-elements-of-array-b) – hakre Jul 22 '11 at 09:37
  • Take a look at [array_diff()](http://php.net/array_diff) – wonk0 Jul 22 '11 at 09:07

5 Answers5

4

array_diff[Docs] returns an array containing all the entries from the first array that are not present in any of the other arrays:

$return = (bool) count(array_diff($ar, $xy));
hakre
  • 193,403
  • 52
  • 435
  • 836
rabudde
  • 7,498
  • 6
  • 53
  • 91
2

You might use array_intersect

With some additional code (thanks Brendan):

return (count($ar) == count(array_intersect($xy, $ar)));
Markus
  • 1,772
  • 1
  • 12
  • 20
0
$found = true;
foreach ($ar as $r) {
    if (!in_array($r, $xy)) {
        $found = false;
        break;
    }
}
Grim...
  • 16,518
  • 7
  • 45
  • 61
0
function array_equal($ar, $xy) {
  return !array_diff($ar, $xy) && !array_diff($ar, $xy);
}

This is how you use it.

if(array_equal($ar, $xy) {
  // etc...
}
JK.
  • 5,126
  • 1
  • 27
  • 26
0
function in_array_all($x, $y){

    $true = 0;
    $count = count($x);

    foreach($x as $key => $value){
        if(in_array($value, $y)) $true++;
    }

    return ($true == $count)? true: false;

}

$ar = array("a","b","c"); $xy = array("a","b","c","d","e");

echo in_array_all($ar, $xy);
Dejan Marjanović
  • 19,244
  • 7
  • 52
  • 66