2

I'm trying to create a function to return true if all items in $array1 are in $array2, if not return false.

What I'm trying to do:

$array1 = ['1', '3', '9', '17'];
$array2 = ['1', '2', '3', '4', '9', '11', '12', '17'];

function checkArray($arr, $arr2) {
    If all elements in $arr are in $arr2 return true
    else return false
}

if (checkArray($array1, $array2) {
    // Function returned true
} else {
    // Function returned false
}

I can't think of how to do this! Help much appreciated.

SOLUTION:

function checkArray($needles, $haystack) {
    $x = array_diff($needles, $haystack);
    if (count($x) > 0) {
        return false;
    } else {
        return true;
    }
}
// Returns false because more needles were found than in haystack
checkArray([1,2,3,4,5], [1,2,3]); 
// Returns true because all needles were found in haystack
checkArray([1,2,3], [1,2,3,4,5]);
2
  • Why not just use array_diff ??? Commented Mar 26, 2013 at 21:01
  • Didn't know about this, feel like an eejit now lol :) thanks for the help! Commented Mar 26, 2013 at 21:08

2 Answers 2

2
function checkArray($arr, $arr2) {
    return !count(array_diff($arr, $arr2));
}

array_diff: Returns an array containing all the entries from $arr that are not present in $arr2. http://php.net/manual/en/function.array-diff.php

Sign up to request clarification or add additional context in comments.

1 Comment

Didn't find this when searching!! Ahh you're a legend, good man cheers!
1

I'm not really sure as to how array_diff is useful in any way. So who cares if there are diferences? You are not comparing arrays, or at least that's not what I understand in the question. You want to know if one array contains the other.

PHP has a handy function for that

function checkArray($arr, $arr2) {
    return (array_intersect($arr, $arr2) == $arr);
}

6 Comments

Now you've confused me... Gonna give this array_diff a try. I also got my problem solved in a totally different way but definitely far from the best solution!
array_dif will give you an array containing differences. But you want to know if one array values are contained in the other, right? Running array_diff just by itself won't give you much.
Well if the count of the differences is greater than zero then not everything in $array1 was found in $array2. Or at least that's how I'm interpreting it! either way both have taught me something new :)
@Think array_diff([1,2,3],[1,2,3,4]) is empty. It won't return that [4].
@joeframbach Of course not, why would I? (Plus don't have priviledges for that yet). I did try array_diff and it turns out it doesn't work exactly as I expected. Thanks for the clarification.
|

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.