"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > How to Merge and Deduplicate Arrays of Objects Based on Unique Email Values?

How to Merge and Deduplicate Arrays of Objects Based on Unique Email Values?

Posted on 2025-03-25
Browse:217

How to Merge and Deduplicate Arrays of Objects Based on Unique Email Values?

Merging and Deduplicating Arrays of Objects with Unique Email Values

In the realm of data manipulation, the task of merging arrays while eliminating duplicate values can be encountered. When working with arrays of objects, it becomes essential to handle such scenarios effectively.

Consider a need to merge two arrays of objects, where each object contains an email property. The goal is to create a new array that contains all unique email values.

Sample Arrays:

$array1 = [
    (object) ["email" => "gffggfg"],
    (object) ["email" => "[email protected]"],
    (object) ["email" => "wefewf"],
];

$array2 = [
    (object) ["email" => "[email protected]"],
    (object) ["email" => "wefwef"],
    (object) ["email" => "wefewf"],
];

Expected Result:

[
   (object) ['email' => 'gffggfg'],
   (object) ['email' => '[email protected]'],
   (object) ['email' => 'wefewf'],
   (object) ['email' => '[email protected]'],
   (object) ['email' => 'wefwef'],
]

Solution:

To merge the arrays and remove duplicates, PHP offers two useful functions:

  • array_merge(): Merges the elements of multiple arrays into a single array.
  • array_unique(): Removes duplicate values from an array.

By combining these functions, we can achieve the desired result:

$array = array_unique (array_merge ($array1, $array2));

This code snippet merges the two input arrays using array_merge() and then eliminates any duplicate email values using array_unique(). The resulting array, stored in $array, contains the distinct email values from both arrays.

Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3