PHP Comparing 2 Arrays For Existence of Value in Each
I have 2 arrays. I simply want to know if one of the values in array 1 is present in array 2. Nothing more than re开发者_如何转开发turning a boolean true or false
Example A:
$a = array('able','baker','charlie');
$b = array('zebra','yeti','xantis');
Expected result = false
Example B:
$a = array('able','baker','charlie');
$b = array('zebra','yeti','able','xantis');
Expected result = true
So, would it be best to use array_diff() or array_search() or some other simple PHP function?
Thanks!
A simple way to do this is to use array_intersect and check if it isn't empty.
$a = array('able','baker','charlie');
$b = array('zebra','yeti','xantis');
echo !!array_intersect($a, $b) ? 'true' : 'false'; //false
$a = array('able','baker','charlie');
$b = array('zebra','yeti','able','xantis');
echo !!array_intersect($a, $b) ? 'true' : 'false'; //true
Or you can make a simple function to check if there is at least one intersection. This is faster than the first one because it doesn't have to find all the intersections. When it finds one, it returns true at that moment.
function check_for_intersect($a, $b) {
$c = array_flip($a);
foreach ($b as $v) {
if (isset($c[$v])) return true;
}
return false;
}
$a = array('able','baker','charlie');
$b = array('zebra','yeti','xantis');
echo check_for_intersect($a, $b) ? 'true' : 'false';
$a = array('able','baker','charlie');
$b = array('able','zebra','yeti','xantis');
echo check_for_intersect($a, $b) ? 'true' : 'false';
You could do something with array_intersect()
if you want to check for a specific number of matches:
if (count(array_intersect($a, $b)) == 1)
{
// > 0, one or more elements from $a is also in $b
// == 1, one element matches, etc.
}
If you just want to see if any element is there:
$new = array_intersect($a, $b);
if (!empty($new)) { ... }
You could use array_intersect() for that!
I found using array search
function check_for_intersect($a, $b)
foreach($a as $h)
if (array_search($h,$b) !== false) {
return true;
}
return false;
}
is much faster than doing an array_intersect when using arrays with lots of elements, because you can save lot of time searching only for the first element occurrence instead for all.
精彩评论