I need something like in_array()
for search if at least one of $foo
is in $bar
array, like:
$foo = array("ESD", "RED", "IOP");
$bar = array("IOD", "MNP", "JDE", "RED");
if(in_array($foo, $bar)) // true because RED is in $foo and in $bar
Thank you in advance!
in_array() function is utilized to determine if specific value exists in an array. It works fine for one dimensional numeric and associative arrays.
The in_array() function searches an array for a specific value. Note: If the search parameter is a string and the type parameter is set to TRUE, the search is case-sensitive.
The array_intersect() function compares the values of two (or more) arrays, and returns the matches. This function compares the values of two or more arrays, and return an array that contains the entries from array1 that are present in array2, array3, etc.
The main difference between both the functions is that array_search() usually returns either key or index whereas in_array() returns TRUE or FALSE according to match found in search.
I think you want array_intersect()
:
$matches = array_intersect($foo, $bar);
$matches
will return an array of all items that are in both arrays, so you can:
empty($matches)
count($matches)
Reference: http://php.net/manual/en/function.array-intersect.php
Example for your case:
$foo = array("ESD", "RED", "IOP");
$bar = array("IOD", "MNP", "JDE", "RED");
// Just cast to boolean
if ((bool) array_intersect($foo, $bar)) // true because RED is in $foo and in $bar
Best is to create your own function if it always is about 2 arrays;
function in_both_arrays($key, $arrone, $arrtwo)
{
return (in_array($key, $arrone) && in_array($key, $arrtwo)) ? true : false ;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With