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

Description: Write a PHP program to find out if an array is a subset of another array.

Rules and hints:

  • The first array is large, and the second array is small.
  • The second array is a subset if all of its values exist in the first array.
  • You can use decision making statements.

PHP program to check if an array is a subset of another

<?php
$array1 = ["a", "1", "2", "3", "4"];
$array2 = ["a", "3"];
$array3 = ["a", "z"];

// array_diff gives the values of the first array that are missing in the second
if (count(array_diff($array2, $array1)) === 0) {
    echo "array2 is a subset of array1<br>";
} else {
    echo "array2 is not a subset of array1<br>";
}

if (count(array_diff($array3, $array1)) === 0) {
    echo "array3 is a subset of array1";
} else {
    echo "array3 is not a subset of array1";
}
?>

Output:

Tutorials Class - Output Window

array2 is a subset of array1
array3 is not a subset of array1

How it works

  • array_diff($array2, $array1) returns the values of $array2 that are not in $array1.
  • If nothing is missing (the count is 0), all values exist, so it is a subset.
  • “z” is not in $array1, so $array3 is not a subset.

Another way: the result of array_intersect($array2, $array1) must have the same count as $array2. See PHP Array Functions.


Learn more about the similar topics:
Tutorials
PHP Arrays
Exercises & Assignments
Remove specific element by value from an array in PHP?
PHP Array to String Conversion (favourite colours chosen by user)
How to check if an array is a subset of another in PHP?
Interview Questions & Answers
No Content Found.