How to use array_intersect() Function In PHP
The array_intersect() function returns an array of values that are present in all the input arrays. If the intersection of the subset array and the superset array has the same number of elements as the subset array, then the subset is entirely contained within the superset.
- array_intersect($subset, $superset) returns an array containing elements found in both $subset and $superset.
- If the count of this intersection equals the count of $subset, then $subset is a subset of $superset.
Example: This example shows the checking of if an array is a subset of another array using array_intersect() function.
<?php
function isSubset($subset, $superset) {
return count(array_intersect($subset, $superset)) == count($subset);
}
// Driver code
$subset = [1, 2, 3];
$superset = [1, 2, 3, 4, 5];
if (isSubset($subset, $superset)) {
echo "Array is a subset";
} else {
echo "Array is not a subset";
}
?>
Output
Array is a subset
Check Whether an Array is Subset of Another Array in PHP
Given two arrays i.e. subset and superset, the task is to check whether an array is subset of another array in PHP. This article covers various methods to determine whether an array is a subset of another array.
These are the following approaches:
Table of Content
- Using array_diff() Function
- Using array_intersect() Function
- Using Loops and in_array() Function
Contact Us