Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

array_intersect, but for a sub-arrays of a single array variable

Tags:

arrays

php

I've got an array that looks like this:

$foo = array(
    0 => array('a', 'b', 'c', 'd'),
    1 => array('b', 'c', 'd'),
    2 => array('b', 'd', 'f')
)

I'll refer to $foo[0], $foo[1], and $foo[2] as sub-arrays.

I basically need to perform an array_intersect() across all 3 sub-arrays in $foo. The result should be:

array('b', 'd')

As all three sub-arrays had these values in common. What is the best way to do this?

Some considerations:

  • There will always be at least one sub-array. No upper limit.
  • If only one sub-array is provided, it should return that sub-array
  • If there aren't any common values in all the sub-arrays, an empty array should be returned
  • If this functionality already exists as a PHP function, I will /facepalm
like image 333
Colin O'Dell Avatar asked Feb 24 '12 21:02

Colin O'Dell


People also ask

How to match 2 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 array intersect?

The intersection of two arrays is a list of distinct numbers which are present in both the arrays. The numbers in the intersection can be in any order. For example. Input: A[] = {1,4,3,2,5, 8,9} , B[] = {6,3,2,7,5} Output: {3,2,5}

How do you check if an array exists in another array PHP?

The in_array() function is an inbuilt function in PHP that is used to check whether a given value exists in an array or not. It returns TRUE if the given value is found in the given array, and FALSE otherwise.


1 Answers

$intersect = call_user_func_array('array_intersect',$foo);

Note that keys are preserved from $foo[0]

like image 93
Mark Baker Avatar answered Sep 29 '22 12:09

Mark Baker