Home  >  Article  >  Backend Development  >  How to detect if an array is a subset of another array via PHP

How to detect if an array is a subset of another array via PHP

藏色散人
藏色散人Original
2021-08-16 11:02:552330browse

As the title says, this article will introduce to you how to determine whether an array is a subset of another array through PHP. What does subset mean? Although everyone may know it, I will still introduce the concept of subset to you by the way~

The introduction to subset is as follows:

Subset is actually a mathematical concept : If any element of set A is an element of set B, then set A is called a subset of set B.

After briefly understanding what a subset is, let’s go directly to the code:

The PHP code is as follows:

<?php
// 定义两个数组
$array1 = array(&#39;a&#39;,&#39;1&#39;,&#39;2&#39;,&#39;3&#39;,&#39;4&#39;);
$array2 = array(&#39;a&#39;,&#39;3&#39;);

if (array_intersect($array2, $array1) === $array2) {
    echo "它是一个子集";
} else {
    echo "它不是一个子集";
}

Output:

它是一个子集

In this code, we define two arrays.

The first array is very large, with 6 values;

The second array is very small, with 2 values;

And when we search for the second array Is it a subset of the first array, which means that all values ​​of the second array should be present in the first array.

Here we will introduce to you a functionarray_intersect()Function:

array_intersect()The function is used to compare two (or more Key values ​​of multiple) arrays and return the intersection.

This function compares the key values ​​​​of two (or more) arrays and returns the intersection array, which includes everything in the compared array (array1) and any other parameter arrays ( key values ​​in array2 or array3 etc.).

The return value of this function is: return the intersection array, which includes all key values ​​in the compared array (array1) and in any other parameter array (array2 or array3, etc.) .

Finally, I would like to recommend the latest and most comprehensive "PHP Video Tutorial"~ Come and learn!

The above is the detailed content of How to detect if an array is a subset of another array via PHP. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn