I have two arrays, first as old, second as new. I want compare both of them and output only duplicates.
I try somethings with a pain : array_intersect
and array_search
without any results...
$oldArray = [
['id' => 'old_id_1', 'color' => 'red'],
['id' => 'old_id_2', 'color' => 'blue'],
['id' => 'old_id_3', 'color' => 'green'],
['id' => 'old_id_4', 'color' => 'purple'],
['id' => 'old_id_5', 'color' => 'yellow'],
];
$newArray = [
['id' => 'new_id_1', 'color' => 'blue'],
['id' => 'new_id_2', 'color' => 'pink'],
['id' => 'new_id_3', 'color' => 'purple'],
];
As return, I want make something like :
We find 2 duplicates colors :
- blue (new_id_1) in old_id_2
- purple (new_id_3) in old_id_4
Try this:
$firstArr = [
['id' => 'old_id_1', 'color' => 'red'],
['id' => 'old_id_2', 'color' => 'blue'],
['id' => 'old_id_3', 'color' => 'green'],
['id' => 'old_id_4', 'color' => 'purple'],
['id' => 'old_id_5', 'color' => 'yellow'],
];
$secondArr = [
['id' => 'new_id_1', 'color' => 'blue'],
['id' => 'new_id_2', 'color' => 'pink'],
['id' => 'new_id_3', 'color' => 'purple'],
];
$firstArrAssoc = array_combine(array_column($firstArr, 'color'), array_column($firstArr, 'id'));
$duplicatesArr = [];
foreach ($secondArr as $row) {
if (array_key_exists($row['color'], $firstArrAssoc)) {
$duplicatesArr[] = "- $row[color] ($row[id]) in {$firstArrAssoc[$row['color']]}";
}
}
echo "We find " . count($duplicatesArr) . " duplicates colors :\n";
echo implode("\n", $duplicatesArr);
Output:
We find 2 duplicates colors :
- blue (new_id_1) in old_id_2
- purple (new_id_3) in old_id_4