Home  >  Article  >  Backend Development  >  How to determine whether an array is in an array in php

How to determine whether an array is in an array in php

PHPz
PHPzOriginal
2023-04-27 09:04:35550browse

In PHP development, we often need to determine whether an array is in another array.

For example, there is a scenario where there is an array A. We need to determine whether all the elements in array A exist in another array B.

In PHP, determining whether an array is in another array can be achieved through the in_array() function. However, this function cannot determine whether one array is completely contained in another array. Therefore, we need to write a function ourselves to implement this function.

The following is the implementation of a custom function:

function array_in_array($needle, $haystack) {
    $result = true;
    foreach ($needle as $value) {
        if (!in_array($value, $haystack)) {
            $result = false;
            break;
        }
    }
    return $result;
}

This function accepts two parameters: $needle and $haystack.

$needle represents the array to be judged, and $haystack represents the array to be judged.

The return value of the function is a Boolean type, indicating whether $needle is completely included in $haystack.

The following is a usage example:

$arrayA = array('apple', 'banana', 'orange');
$arrayB = array('orange', 'banana', 'apple', 'pear');

$result = array_in_array($arrayA, $arrayB);

if ($result) {
    echo '数组A中所有元素都在数组B中';
} else {
    echo '数组A中存在元素不在数组B中';
}

In the above example, $arrayA contains 3 elements and $arrayB contains 4 elements. All elements in $arrayA exist in $arrayB. Therefore, the value of $result is true, and the program will output "All elements in array A are in array B."

If $arrayB is changed to the following:

$arrayB = array('orange', 'banana');

After executing the above code, the program will output "The elements present in array A are not in array B".

This function is relatively simple, the key is to understand the principle.

We can traverse the elements in $needle through a foreach loop, and then determine whether each element is in $haystack. If there is an element that is not in $haystack, it means that $needle is not a subset of $haystack, and the function returns false.

In this way, we can easily determine whether an array is in another array!

The above is the detailed content of How to determine whether an array is in an array in 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