Roshan Bhumbra Roshan Bhumbra - 24 days ago 11
PHP Question

Find repeating values in multidimensional array

I'm trying to find when the array has 2nd dimension values that are the same so I can deal with them.

I've looked at

array_unique
and other people who are asking a similar question, but they all delete the values instead of returning them.

Say I have an array like this:

array(
[0] => array(
[laps] => 7,
[corrected_time] => 18
),
[1] => array(
[laps] => 6,
[corrected_time] => 18
),
[2] => array(
[laps] => 7,
[corrected_time] => 18.5
)
)


I'd like to have it return:
array(0,1)
because they both have the same value for
corrected time

Answer

This appears to do what you're asking, unless I've misunderstood the question:

$arr = array(0 => array('laps' => 7,
                        'corrected_time' => 18),
             1 => array('laps' => 6,
                        'corrected_time' => 18),
             2 => array('laps' => 7,
                        'corrected_time' => 18.5));

// remove duplicates on column 'laps'
var_dump(array_intersect_key($arr, array_unique(array_column($arr, 'laps'))));

Output:

array(2) {
  [0]=>
  array(2) {
    ["laps"]=>
    int(7)
    ["corrected_time"]=>
    int(18)
  }
  [1]=>
  array(2) {
    ["laps"]=>
    int(6)
    ["corrected_time"]=>
    int(18)
  }
}

Explanation:

array_column is used to isolate the column you want, it will return an array with numeric keys. This gives us the following:

array(3) {
  [0]=>
  int(7)
  [1]=>
  int(6)
  [2]=>
  int(7)
}

array_unique will return an array with any duplicates removed. The result is now:

array(2) {
  [0]=>
  int(7)
  [1]=>
  int(6)
}

Finally, array_intersect_key will compute the intersection of the original array with the unique array using the keys for comparison. In other words, it returns an array where the keys match.

Comments