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.

6
  • Take a look at array_diff() Commented Jul 22, 2011 at 9:07
  • possible duplicate of PHP - Check if two array are equal Commented Jul 22, 2011 at 9:15
  • @gordon: That dupe checks for equality which won't work for this question. However a good related one. Commented Jul 22, 2011 at 9: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. Commented Jul 22, 2011 at 9: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. Commented Jul 22, 2011 at 9:36

5 Answers 5

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

5 Comments

no need for the ternary here; guess what count( ... ) > 0 gives you ;)
it gives me the number of elements in $ar which are not in $xy
count( ... ) gives you the number; count( ... ) > 0 gives you a boolean
@rabudde The evaluation of the count(...) > 0 already gives you your boolean value. No need for the manual assignment: $return = (count(array_diff($ar, $xy)) > 0);
Just cast. Everything non-0 is true.
2

You might use array_intersect

With some additional code (thanks Brendan):

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

1 Comment

Good answer but some code would be useful. Maybe: return (count($ar) == count(array_intersect($xy,$ar)));?
0
$found = true;
foreach ($ar as $r) {
    if (!in_array($r, $xy)) {
        $found = false;
        break;
    }
}

Comments

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

Comments

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

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.