Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I use in_array if the needle is an array?

I have 2 arrays, the value will be loaded from database, below is an example:

$arr1 = array(1,2,3); $arr2 = array(1,2,3,4,5,6,7); 

What I want to do is to check if all the values in $arr1 exist in $arr2. The above example should be a TRUE while:

$arr3 = array(1,2,4,5,6,7); 

comparing $arr1 with $arr3 will return a FALSE.

Normally I use in_array because I only need to check single value into an array. But in this case, in_array cannot be used. I'd like to see if there is a simple way to do the checking with a minimum looping.

UPDATE for clarification.

First array will be a set that contains unique values. Second array can contain duplicated values. They are both guaranteed an array before processing.

like image 462
Donny Kurnia Avatar asked Feb 21 '10 01:02

Donny Kurnia


People also ask

Does in_array work for associative array?

in_array() function is utilized to determine if specific value exists in an array. It works fine for one dimensional numeric and associative arrays.

What is the use of in_array () function?

The in_array() function is an inbuilt function in PHP that is used to check whether a given value exists in an array or not. It returns TRUE if the given value is found in the given array, and FALSE otherwise.

How do you find the value of an array?

JavaScript Array includes() The includes() method returns true if an array contains a specified value. The includes() method returns false if the value is not found.


2 Answers

Use array_diff():

$arr1 = array(1,2,3); $arr2 = array(1,2,3,4,5,6,7); $arr3 = array_diff($arr1, $arr2); if (count($arr3) == 0) {   // all of $arr1 is in $arr2 } 
like image 193
cletus Avatar answered Sep 20 '22 17:09

cletus


You can use array_intersect or array_diff:

$arr1 = array(1,2,3); $arr2 = array(1,2,3,4,5,6,7);  if ( $arr1 == array_intersect($arr1, $arr2) ) {     // All elements of arr1 are in arr2 } 

However, if you don't need to use the result of the intersection (which seems to be your case), it is more space and time efficient to use array_diff:

$arr1 = array(1,2,3); $arr2 = array(1,2,3,4,5,6,7); $diff = array_diff($arr1, $arr2);  if ( empty($diff) ) {     // All elements of arr1 are in arr2 } 
like image 35
Justin Johnson Avatar answered Sep 22 '22 17:09

Justin Johnson