3
\$\begingroup\$

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?

asked Apr 19, 2013 at 21:42
\$\endgroup\$

2 Answers 2

4
\$\begingroup\$

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;
 }
}
answered Apr 19, 2013 at 22:26
\$\endgroup\$
0
2
\$\begingroup\$

In addition to p.w.s.g's answer (which seems fine):

If you have lots of values you need to find, you can use a hash:

// the values go into keys of the array
$needles = array('value1' => 1, 'value2' => 1, 'value3' => 1);
$haystack = array('test', 'value1', 'etc');
// only go through the array once
$found = false;
foreach($haystack as $data) {
 if (isset($needles[$data])) {
 $found = true; break;
 }
 }

It's worth doing this if you search $haystack a lot of times.

answered Apr 21, 2013 at 6:09
\$\endgroup\$

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.