I have this code to remove duplicates (all occurrences) from an associative array, does PHP have methods to do this ? Or is there a way to improve the code ?
I looked for array_unique, array_search, array_map, array_reduce...
$articles = [
[
"id" => 0,
"title" => "lorem",
"reference" => "A"
],
[
"id" => 1,
"title" => "ipsum",
"reference" => "B"
],
[
"id" => 2,
"title" => "dolor",
"reference" => "C"
],
[
"id" => 3,
"title" => "sit",
"reference" => "A"
]
];
$references = array_column($articles, "reference");
$duplicates = array_values(array_unique(array_diff_assoc($references, array_unique($references))));
foreach($duplicates as $duplicate) {
foreach($references as $index => $reference) {
if($duplicate === $reference) {
unset($articles[$index]);
}
}
}
/**
* $articles = [
* [
* "id" => 1,
* "title" => "ipsum",
* "reference" => "B"
* ],
* [
* "id" => 2,
* "title" => "dolor",
* "reference" => "C"
* ]
* ]
*/