Search code examples
phparraysforeach

Checking if a values from array exists in a second array in PHP


I am trying to check if any of the values from array 1 exist in array 2. I am currently trying to achieve this using a combination of foreach and in_array:

Array 1:

Array
(
    [checkThis1] => 1234567
    [checkThis2] => 7654321
    [checkThis3] => 0101010
)

Array 2:

Array
(
    [0] => 0101010
    [1] => 9324812
)

Code:

foreach ($array1 as $checkThis) {
        if (in_array($checkThis, $array2)) {
            echo "checkThis exists in array2";
            return true;
        }
        echo "checkThis does not exist in array2";
        return false;
    }

As you can see up here the two arrays are formatted the same way so this should cause no issues. For some reason unknown to me this loop always returns false, even though I am sure that the value exists in both of the arrays.


Solution

  • return ends code execution. Your foreach is only completing its first iteration. If 0101010 was the first item in the first array it would return true. To get the items that exist in both arrays use array_intersect.

    $arrayOne = [
        'checkThis1' => 1234567,
        'checkThis2' => 7654321,
        'checkThis3' => 0101010
    ];
    
    $arrayTwo = [0101010, 9324812];
    
    $intersect = array_intersect(array_values($arrayOne), $arrayTwo);
    

    To check if any of the items exist in the second array check if the count of the intersect is bigger than 0.

    $hasAny = (count(array_intersect(array_values($arrayOne), $arrayTwo)) > 0); // true or false