Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

I have a multidimensional array containing three arrays and an array of id's within each. Here is what it looks like:

$data = array(
    'first' => array(1,2,3,4,5,6),
    'second' => array(1,2,3),
    'third' => array(1,2,5,6)
);

What I'd like to do is run an intersection on all three and end up with the result of an array, in this example, would be array(1,2)

How do I accomplish this?

share|improve this question

4 Answers 4

up vote 2 down vote accepted
$newArray = array_values(call_user_func_array("array_intersect", $data));

array_intersect returns the identical values of all the arrays passed, so you can pass the entries of $data as arguments to it. array_values is needed for reindexing as the keys won't be changed (not necessary, but helpful when you use the resulting array in a for loop).

share|improve this answer

using array_reduce and array_intersect.

$v = array_values($data);
$r = array_slice($v, 1);
$result = array_reduce($r, 'array_intersect', $v[0]);
var_dump($result);

Here is a one-liner.

array_reduce(array_slice($data, 0, -1), 'array_intersect', end($data));
share|improve this answer
    
Nice solution.. –  vascowhite Jun 1 '13 at 22:08
    
@raina here to you. Added a one-liner –  shiplu.mokadd.im Jun 1 '13 at 22:10
    
I saw that, ok. ) What I yet to see is how this is better than using call_user_func_array, though. –  raina77ow Jun 1 '13 at 22:13
    
using array_reduce was too obvious for me to see ;) nice work, i guess my code does exactly the same, but sadly it is already built in... –  luk2302 Jun 1 '13 at 22:13
    
@shiplu.mokadd.im Nice solution, but sadly array_reduce needs an initial value here. This reduces a bit the beauty of the solution... –  bwoebi Jun 1 '13 at 22:23

what about the following approach:

$comp = null;
foreach ($data as $arr) {
  if ($comp === null) {
    $comp = $arr;
    continue;
  } else {
    $comp = array_intersect($comp, $arr);
  }
}
//$comp no contains all the unique values;

btw: works with any count of $data except $data = null

share|improve this answer

The simplest way to solve this is with array_reduce:

function process($result, $item) {
    return is_null($result) ? $item : array_intersect($result, $item);
}
$result = array_reduce($data, 'process');

Or use array_reduce with an anonymous function like this:

$result = array_reduce($data, function($result, $item) {
    return is_null($result) ? $item : array_intersect($result, $item);
});

This last solution has the advantage of not needing to reference a function (built-in or otherwise) using a string containing the function name.

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.