Php checks if an array contains all array values ​​from another array

$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 know if $ all contains all the values ​​of $ search_this and returns true or false. any idea please?

+63
arrays php
Mar 11 2018-12-12T00:
source share
5 answers

Take a look at array_intersect () .

 $containsSearch = count(array_intersect($search_this, $all)) == count($search_this); 
+114
Mar 11 2018-12-12T00:
source share

The previous answers all do more work than necessary. Just use array_diff . This is the easiest way to do this:

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

That is all you have to do.

+107
Mar 26 '14 at 3:50
source share

A bit shorter than 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 
+7
Mar 10 '14 at 17:48
source share

I think you are looking for an intersection 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 arguments. Please note that keys are saved.

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

+2
Mar 11 2018-12-12T00:
source share

How about this:

function array_keys_exist($searchForKeys = array(), $searchableArray) { $searchableArrayKeys = array_keys($searchableArray); return count(array_intersect($searchForKeys, $searchableArrayKeys)) == count($searchForKeys); }

0
Nov 18 '17 at 14:03
source share



All Articles