-3

I want to compare all the sub arrays in the $ids and I want to return only the numbers that show up in all three arrays, so it would return 3 and 4 as an array.

$ids = [
    [1,2,3,4],
    [2,3,4],
    [3,4,5],
];

expecting it to return

array(3,4)

UPDATE: My apologies, I left out the detail that I would not know how many arrays would be in the associative array, it could be 2 sub arrays, other times it could be 5. I appreciate all the answers I have received.

Brad
  • 12,054
  • 44
  • 118
  • 187
  • Not a duplicate, I am trying to compare a multi associate array, the one you linked to is a normal array. – Brad Jan 31 '19 at 20:26
  • 1
    I would have thought that working with 2 arrays is a short extension to what is in effect 3 arrays. The end result is exactly what the duplicate indicated - `array_intersect()`. – Nigel Ren Jan 31 '19 at 20:39
  • @NigelRen: I agree in a way, however you would need to use `array_intersect($ids[0], $ids[1], $ids[2])` assuming that you know there are 3 elements, and that they are integer indexes and that they are consecutive from 0. – AbraCadaver Jan 31 '19 at 20:51
  • @AbraCadaver - I thought duplicates weren't necessarily a case of *cut and paste* the answer - sometimes you will need to adapt it to your particular scenario. The 2 answers both provide ways of applying `array_intersect()`. – Nigel Ren Jan 31 '19 at 21:01

2 Answers2

2

Splice out the first subarray and then loop the rest and use array_intersect to filter the result to 3,4.

$res = array_splice($ids,0,1)[0];

foreach($ids as $id){
    $res = array_intersect($res, $id);
}

var_dump($res); // 3,4

https://3v4l.org/Z7uZK

Andreas
  • 23,610
  • 6
  • 30
  • 62
2

Obviously array_intersect is the solution How to get common values from two different arrays in PHP. If you know the number of sub-arrays and their indexes then it's as simple as:

$result = array_intersect($ids[0], $ids[1], $ids[2]);

However, if you need to do it for an unknown/variable number of sub-arrays and/or unknown indexes, use $ids as an array of arguments with call_user_func_array:

$result = call_user_func_array('array_intersect', $ids);

Or better use Argument unpacking via ... (PHP >= 5.6.0):

$result = array_intersect(...$ids);
AbraCadaver
  • 78,200
  • 7
  • 66
  • 87
  • And if you want to re-key: `array_values(array_intersect(...$ids));` – Progrock Jan 31 '19 at 23:02
  • I should of provided more details, I failed to mention that the associative array would not have a known amount of arrays in it, it is being dynamically created so it could have 2 arrays one time, and 5 the next time it is ran. – Brad Feb 01 '19 at 14:45