Question

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?

Was it helpful?

Solution

$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).

OTHER TIPS

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));

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

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top