10

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
1

1 Answer 1

31
+50
$intersect = call_user_func_array('array_intersect',$foo);

Note that keys are preserved from $foo[0]

Sign up to request clarification or add additional context in comments.

2 Comments

Clever approach, I like it! It works fine if $foo has at least 2 sub-arrays, but fails if there's just one. I fixed this by only calling the above if count($foo) > 1. If count($foo) == 1 I just return the only sub-array. Thanks!
Thank you @ColinO'Dell $currencies = count($currencies) > 1 ? call_user_func_array('array_intersect', $currencies) : array_shift($currencies); NOTE: I'm typecasting (array) on $currencies so that array_shift returns [].

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.