phparraysmultidimensional-arrayintersection

Get values that occur in each row of a 2d array


From a function I am given a multidimensional array like this:

[
    [7, 18],
    [12, 7],
    [12, 7, 13],
]

I need to find duplicate values in the 3 arrays within the main array. For example, if value 7 repeats in the 3 arrays, return 7.


Solution

  • <?php
    $array = array(array(7,18), array(12,7), array(12, 7, 13));
    $result = array();
    
    
    $first = $array[0];
    for($i=1; $i<count($array); $i++){
     $result = array_intersect ($first, $array[$i]);
     $first = $result;
    }
    print_r($result);//7
    ?>