When working with arrays of objects, it may become necessary to merge multiple arrays into a single one while ensuring the elimination of duplicate values. To achieve this, we can leverage the capabilities of PHP's built-in array functions.
Merging the Arrays
The array_merge() function comes in handy when combining two or more arrays. It appends the elements of the second array to the first, creating a new array with all the elements from both. In this case, we can use it to merge the two input arrays, $array1 and $array2, into a single array.
Removing Duplicates
To remove duplicate values, we can utilize the array_unique() function. It returns a new array with only the unique values from the input array. Duplicates are identified and excluded from the result.
Combining the Functions
By combining these two functions, we can achieve our desired goal. We first merge the two input arrays using array_merge() and then apply array_unique() to eliminate duplicate values. Here's how it looks:
$array = array_unique(array_merge($array1, $array2));
This code snippet will create a new array, $array, containing the unique objects from both $array1 and $array2. The duplicate emails will be removed.
Example Usage
Consider the following example:
$array1 = [ (object) ["email" => "gffggfg"], (object) ["email" => "example@email.com"], (object) ["email" => "wefewf"], ]; $array2 = [ (object) ["email" => "example@email.com"], (object) ["email" => "wefwef"], (object) ["email" => "wefewf"], ]; $array = array_unique(array_merge($array1, $array2)); print_r($array);
This code will produce the following output:
Array ( [0] => stdClass Object ( [email] => gffggfg ) [1] => stdClass Object ( [email] => example@email.com ) [2] => stdClass Object ( [email] => wefewf ) [3] => stdClass Object ( [email] => wefwef ) )
As you can see, the duplicate email value, "example@email.com", has been removed from the merged array.
The above is the detailed content of How to Merge Object Arrays and Remove Duplicates in PHP?. For more information, please follow other related articles on the PHP Chinese website!