phparraysvalidationintersectionshort-circuiting

Determine if any value from a flat array exists in another flat array


$array = ['a', 'b', 'c', 'd'];
$vars = ['a', 'f', 'g'];

foreach ($vars as $var) {
    if (in_array($var, $array)) {
        return true;
    } else {
        return false;
    }
}

How can i check if one of the $vars exists in $array? Only one of them needs to be true if all the others are false it is not a problem, But if there is more than 1 true value,

For example ['a', 'b', 'c', 'g'] i want the function to stop at the first true value and ends the process.


Solution

  • For me, the code you've got in the question is pretty much the best way to go about this. You just need to move the return false to after the loop, so that all values get processed:

    foreach ($vars as $var) {
      if (in_array($var, $array)) {
        return true;
      }
    }
    
    return false;
    

    This will work identically to a solution with array_intersect, but has the advantage of only needing to process the minimum amount of the loop. Consider the following data:

    $vars = [1, 2, 3, 4, ... 1,000,000,000];
    $array = [1, 10, ...];
    

    A solution using array_intersect will need check every element in $vars against every element in $array, whereas a solution that breaks out of a loop will only need to check until the first match. You could optimise this further by using two nested foreach loops if both your arrays are very large.

    Like I mentioned in the comment - if your arrays are small then just use array_intersect, you won't notice any difference, and the code is a bit more readable.