SandyK
SandyK

Reputation: 465

find all array elements in another array

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.

Upvotes: 1

Views: 914

Answers (5)

rabudde
rabudde

Reputation: 7722

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

Upvotes: 4

Markus
Markus

Reputation: 1822

You might use array_intersect

With some additional code (thanks Brendan):

return (count($ar) == count(array_intersect($xy, $ar)));

Upvotes: 2

JK.
JK.

Reputation: 5136

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

Upvotes: 0

Dejan Marjanović
Dejan Marjanović

Reputation: 19380

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

Upvotes: 0

Grim...
Grim...

Reputation: 16953

$found = true;
foreach ($ar as $r) {
    if (!in_array($r, $xy)) {
        $found = false;
        break;
    }
}

Upvotes: 0

Related Questions