HiveBrain v1.2.0
Get Started
← Back to all entries
patternphpMinor

Best way to check for one of two values in an array in PHP

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
arrayphpwayonetwoforvaluescheckbest

Problem

I want to see if one of two values (a, b) are in an array. Here's my current thought:

$match_array = array('a','b');
$array_under_test = array('b', 'd', 'f');

if (array_intersect($match_array, $array_under_test)) {
  // Success!
}


Any better implementations?

Solution

If you want to verify that either value is in the $array_under_test, array_intersect may not be the best option. It will continue to test for collisions even after it finds a match.

For two search strings you can just do:

if (in_array('a', $array_under_test) || in_array('b', $array_under_test)) {
  // Success!
}


This will stop searching if 'a' is found in the $array_under_test.

For more than two values, you can use a loop:

foreach ($match_array as $value) {
  if (in_array($value, $array_under_test)) {
    // Success!
    break;
  }
}

Code Snippets

if (in_array('a', $array_under_test) || in_array('b', $array_under_test)) {
  // Success!
}
foreach ($match_array as $value) {
  if (in_array($value, $array_under_test)) {
    // Success!
    break;
  }
}

Context

StackExchange Code Review Q#25276, answer score: 4

Revisions (0)

No revisions yet.