Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Test if one array is a subset of another

Tags:

How can I determine if one array is a subset of another (all elements in the first are present in the second)?

 $s1 = "string1>string2>string3>string4>string5>string6>";
 $arr1 = explode(">", $s1);
 $s2 = "string1>string4>string5";
 $arr2 = explode(">", $s2);

 $isSubset = /* ??? */
like image 226
Kamesh Jungi Avatar asked Sep 05 '12 07:09

Kamesh Jungi


People also ask

How do you check if an array is subset of another array JS?

Naive Approach to Find whether an array is subset of another array. Use two loops: The outer loop picks all the elements of arr2[] one by one. The inner loop linearly searches for the element picked by the outer loop. If all elements are found then return 1, else return 0.

How do you check if an array is a subset of another array in PHP?

Simple: use array subtraction. On array subtraction, you will know whether or not one array is a subset of the other. You can use array_intersect also. array_diff(['a', 'b', 'c'], ['a', 'b']) will return ['c'].

How do you check if an array is a subset of another Python?

Python Set issubset() The issubset() method returns True if set A is the subset of B , i.e. if all the elements of set A are present in set B . Else, it returns False .


2 Answers

if (array_intersect($array1, $array2) == $array1) {
    // $array1 is a subset of $array2
}
like image 63
deceze Avatar answered Oct 05 '22 18:10

deceze


Simple: use array subtraction.

On array subtraction, you will know whether or not one array is a subset of the other.

Example:

if (!array_diff($array1, $array2)) {
    // $array1 is a subset of $array2
}

Reference: array_diff

You can use array_intersect also.

like image 26
shail Avatar answered Oct 05 '22 20:10

shail