Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

php

I need something like in_array() for search if at least one of $foo is in $bararray, 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!

like image 502
udexter Avatar asked May 06 '11 11:05

udexter


People also ask

Does in_array work for associative array?

in_array() function is utilized to determine if specific value exists in an array. It works fine for one dimensional numeric and associative arrays.

What is use of in_array () function in PHP?

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.

How can I get common values from two arrays in PHP?

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.

What is the difference between in_array and Array_search?

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.


2 Answers

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:

  • Check to see if there are no matches with empty($matches)
  • Read the number of matches with count($matches)
  • Read the values of the intersections if you need to

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
like image 130
Wesley Murch Avatar answered Oct 09 '22 04:10

Wesley Murch


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 ;
}
like image 41
Joshua - Pendo Avatar answered Oct 09 '22 03:10

Joshua - Pendo