1

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?

4 Answers 4

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

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

Comments

2

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

6 Comments

@raina here to you. Added a one-liner
I saw that, ok. ) What I yet to see is how this is better than using call_user_func_array, though.
@shiplu.mokadd.im Nice solution, but sadly array_reduce needs an initial value here. This reduces a bit the beauty of the solution...
@shiplu.mokadd.im but the array_slice is unnecessary as an intersection with the same array won't change anything.
@bwoebi it wont change the result. But it'll execute array_intersect on same elements twice. This was prevented by using array_slice.
|
0

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

Comments

0

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.

Comments

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.