PHP

Check if One Array is a Subset of Another

Discover a concise way to determine if all elements of one PHP array are present in another larger array using `array_diff` for subset validation.

$mainArray = [1, 2, 3, 4, 5, 6];
$subsetA = [2, 4];
$subsetB = [7, 1, 3];
$subsetC = [1, 2, 3, 4, 5, 6]; // Equal arrays are also subsets

function isSubset(array $subset, array $superset): bool
{
    return empty(array_diff($subset, $superset));
}

echo "Is subsetA a subset of mainArray? " . (isSubset($subsetA, $mainArray) ? 'Yes' : 'No') . "
"; // Expected: Yes
echo "Is subsetB a subset of mainArray? " . (isSubset($subsetB, $mainArray) ? 'Yes' : 'No') . "
"; // Expected: No
echo "Is subsetC a subset of mainArray? " . (isSubset($subsetC, $mainArray) ? 'Yes' : 'No') . "
"; // Expected: Yes

// For associative arrays, checking keys/values:
$mainAssoc = ['a' => 1, 'b' => 2, 'c' => 3];
$subAssocA = ['a' => 1, 'c' => 3];
$subAssocB = ['a' => 1, 'd' => 4];

// Use array_diff_assoc for key-value strict subset
function isAssocSubset(array $subset, array $superset): bool
{
    return empty(array_diff_assoc($subset, $superset));
}
echo "Is subAssocA a subset of mainAssoc (assoc)? " . (isAssocSubset($subAssocA, $mainAssoc) ? 'Yes' : 'No') . "
"; // Expected: Yes
echo "Is subAssocB a subset of mainAssoc (assoc)? " . (isAssocSubset($subAssocB, $mainAssoc) ? 'Yes' : 'No') . "
"; // Expected: No
How it works: This snippet defines a reusable function `isSubset()` that checks if all elements of `$subset` are present in `$superset`. It leverages `array_diff()`, which returns elements from the first array not present in the second. If the difference is empty, it means all elements of the `$subset` were found in `$superset`. For associative arrays where both keys and values must match, `array_diff_assoc()` is used.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs