How to use array_merge() and array_unique() Function In PHP
The array_merge() function merges the elements of one or more arrays, while the array_unique() function removes duplicate values from an array.
Example: This example shows the use of the above-explained approach.
<?php
// Declare two arrays
$arr1 = [1, 2, 3, 4];
$arr2 = [3, 4, 5, 6];
// Merge the arrays
$mergedArr = array_merge($arr1, $arr2);
// Remove duplicates
$uniqueArr = array_unique($mergedArr);
print_r($uniqueArr);
?>
Output
Array ( [0] => 1 [1] => 2 [2] => 3 [3] => 4 [6] => 5 [7] => 6 )
Explanation:
- array_merge($arr1, $arr2) function combines the elements of $arr1 and $arr2 into a single array.
- array_unique($mergedArr) function removes any duplicate values from the merged array.
Merge Two Arrays & Remove Duplicate Items in PHP
Given two arrays, the task is to merge both arrays and remove the duplicate elements from from merged array in PHP.
Below are the approaches to merge two arrays and remove duplicate items in PHP:
Table of Content
- Using array_merge() and array_unique() Function
- Using array_merge() with array_flip() Function
- Using array_merge() with array_values() and array_filter() Functions