Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.
$all = array
(
    0 => 307,
    1 => 157,
    2 => 234,
    3 => 200,
    4 => 322,
    5 => 324
);
$search_this = array
(
    0 => 200,
    1 => 234
);

I would like to find out if $all contains all $search_this values and return true or false. any idea please?

share|improve this question

4 Answers 4

up vote 45 down vote accepted

Look at array_intersect().

$containsSearch = count(array_intersect($search_this, $all)) == count($search_this);
share|improve this answer
    
thanks, it works! :) –  peter Mar 11 '12 at 14:36
1  
You know you can omit both count() calls? –  Wrikken Aug 15 '13 at 16:01
    
@Wrikken Can't the values get reordered during array_intersect()? I mean, ['a', 'b'] != ['b', 'a']. –  exizt Oct 16 '13 at 18:57
1  
@exizt: array_intersect() does not alter the input arrays, so $search_this & $all are safe (it just returns an output). The function signature is array array_intersect ( array $array1 , array $array2 [, array $... ] ) (safe). If it would/could alter them, it would be array array_intersect ( array &$array1 , array &$array2 [, array &$... ] ) (possible altering of input arguments). Also, the keys of $search_this are preserve, and the order of the first array is kept. So, both key/value pairs, as their order, match. –  Wrikken Oct 16 '13 at 21:03
2  
And even then: array comparison: "== TRUE if $a and $b have the same key/value pairs.", so the order doesn't even matter (use === for that) –  Wrikken Oct 16 '13 at 21:24

The previous answers are all doing more work than they need to. This is the simplest way to do it:

$containsAllValues = !array_diff($search_this, $all);

That's all you have to do.

share|improve this answer
1  
Thanks for the aha moment; I came in thinking array_intersect. –  Derek Illchuk Jul 4 '14 at 22:24

A bit shorter with array_diff

$musthave = array('a','b');
$test1 = array('a','b','c');
$test2 = array('a','c');

$containsAllNeeded = 0 == count(array_diff($musthave, $test1));

// this is TRUE

$containsAllNeeded = 0 == count(array_diff($musthave, $test2));

// this is FALSE
share|improve this answer

I think you're looking for the intersect function

array array_intersect ( array $array1 , array $array2 [, array $ ... ] )
array_intersect() returns an array containing all the values of array1 that are 
present in all the arguments. Note that keys are preserved.

http://www.php.net/manual/en/function.array-intersect.php

share|improve this answer
    
thanks, it works! :) –  peter Mar 11 '12 at 14:37

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.