0

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.

eng
  • 443
  • 1
  • 4
  • 10
Luuc
  • 99
  • 1
  • 9
  • 2
    Don't use `return`s, comment them out and see what the result is. And use `echo "$checkThis ...` instead of `echo "checkThis...` – brombeer Jul 17 '23 at 19:47
  • 2
    Do you mean https://stackoverflow.com/questions/523796/checking-if-any-of-an-arrays-elements-are-in-another-array – Nigel Ren Jul 17 '23 at 19:48
  • 1
    1234567 is not in array2. no idea how you are sure about that, but you didn't convince me ;) – hakre Jul 17 '23 at 19:48
  • @hakre True! But 0101010 is in array2 :) – Luuc Jul 18 '23 at 10:52
  • 1
    @Luuc: See the first comment: `return` exits the loop as well, but you're not yet done with the work. return `false` only _after_ the foreach body, not within. Within, you only return true, because that is already the outcome (there could be more matches, but it is a match already on first match). Only as long there is not yet a match, you have to go on and go on and can only say after processing all items, that there is no match at all (return false). – hakre Jul 18 '23 at 12:53
  • @hakre I've tried this solution and it worked! Now I see what I was doing wrong, thanks :) – Luuc Jul 19 '23 at 12:45

1 Answers1

1

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
D1__1
  • 925
  • 1
  • 3
  • 14
  • I see, so if the first checked value does not exist in array 2, the function exits via return? That would make sense of why it does not work :) – Luuc Jul 18 '23 at 10:54
  • The code that you provided does not show a function, if it is within a function, yes. – D1__1 Jul 18 '23 at 12:21