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 = /* ??? */
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.
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'].
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 .
if (array_intersect($array1, $array2) == $array1) {
// $array1 is a subset of $array2
}
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.
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