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.
in_array() function is utilized to determine if specific value exists in an array. It works fine for one dimensional numeric and associative arrays.
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.
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.
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 }
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 }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With