![]() |
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() FunctionThe array_diff() function computes the difference of arrays. If the result of the difference between the subset array and the superset array is empty, it means all elements of the subset are present in the superset.
Example: This example shows the checking of if an array is a subset of another array using array_diff() function.
Output Array is a subset Using array_intersect() FunctionThe 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.
Example: This example shows the checking of if an array is a subset of another array using array_intersect() function.
Output Array is a subset Using Loops and in_array() FunctionA more manual approach involves looping through each element in the subset array and checking if it exists in the superset array using in_array() function.
Example: This example shows the checking of if an array is a subset of another array using lops and in_array_diff() function.
Output Array is a subset Using array_flip() and array_key_exists() FunctionsThe array_flip() function flips the keys and values of an array. By flipping the superset array and then checking if each element in the subset array exists as a key in the flipped superset array using array_key_exists(), we can determine if the subset is contained within the superset. Steps:
Example: This example shows the checking of if an array is a subset of another array using array_flip() and array_key_exists() functions.
Output Array is a subset Output Array is a subset |
Reffered: https://www.geeksforgeeks.org
PHP |
Type: | Geek |
Category: | Coding |
Sub Category: | Tutorial |
Uploaded by: | Admin |
Views: | 21 |