Doing PHP in_array () but with a needle of another array ()

I need something like in_array()to search if at least one of it $foois in the array $bar, for example:

$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!

+5
source share
3 answers

I think you want array_intersect():

$matches = array_intersect($foo, $bar);

$matches will return an array of all elements in both arrays so you can:

  • Check for matches with empty($matches)
  • Read the number of matches with count($matches)
  • Read intersection values ​​if you need to

Link: http://php.net/manual/en/function.array-intersect.php

An 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
+17
source

It is best to create your own function if it is always about 2 arrays;

function in_both_arrays($key, $arrone, $arrtwo)
{
  return (in_array($key, $arrone) && in_array($key, $arrtwo)) ? true : false ;
}
+1
source
function in_arrays($needles, $haystack)
{
    foreach ((array) $needles as $needle)
    {
        if (in_array($needle, $haystack) === true)
        {
            return true;
        }
    }

    return false;
}
0
source

All Articles