Skip to content
Advertisement

How to check duplicate values in multidimensional associative array?

I have an associative multidimensional array with multiple state ids:

array:2 [
  0 => array:2 [
    "url" => "http://www.kerluke.net/qui-sint-debitis-quo-et-suscipit-dolores-dolor-quae"
    "us_states_ids" => array:2 [
      0 => "15"
      1 => "16"
    ]
  ]
  1 => array:2 [
    "url" => "http://www.migato.net/qui-sint-debitis-quo-et-suscipit-dolores-dolor-quae"
    "us_states_ids" => array:3 [
      0 => "15"
      1 => "24"
      2 => "28"
    ]
  ]
]

Now I want to find duplicate ids for us_states_ids as you can see index 1 has id of 15 same as index 2. How can I achieve this?

Advertisement

Answer

Try looping the array and play around with array_intersect on current “us_state_ids” with the previous one if it is not the first iteration.

$duplicates = [];
for ($i = 1; $i < count($arr); $i++) {
    $prevStateIds = $arr[$i - 1]["us_states_ids"];
    $stateIds = $arr[$i]["us_states_ids"];
    $duplicates = array_merge($dupicates, array_intersect($prevStateIds, $stateIds));
  }
}

then $duplicates will have the duplicates. The above code is untested, it’s just for a reference.

User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement