"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > How to Check for Multiple Values in PHP Arrays Using `in_array()`?

How to Check for Multiple Values in PHP Arrays Using `in_array()`?

Published on 2024-11-23
Browse:914

How to Check for Multiple Values in PHP Arrays Using `in_array()`?

Checking Multiple Values in Arrays with PHP's in_array() Function

PHP's in_array() function, designed for value existence checks, has a limitation when it comes to verifying multiple values simultaneously. This article aims to address this challenge, presenting solutions for both scenarios:

Checking for Presence of All Values

To determine if an array contains all elements from another array, use the following approach:

$haystack = array(...);
$target = array('foo', 'bar');

if (count(array_intersect($haystack, $target)) == count($target)) {
    // all of $target is in $haystack
}

The intersect function finds the common elements between two arrays, and comparing its count to the size of the target array ensures that all target values are present in the haystack.

Checking for Presence of Any Value

In contrast, to verify if the haystack array contains at least one value from the target array, use the following syntax:

if (count(array_intersect($haystack, $target)) > 0) {
    // at least one of $target is in $haystack
}

Here, we check if the count of the intersection is greater than zero, indicating that at least one value from the target array is present in the haystack.

Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3