How to merge two arrays without duplicate values in PHP?

In this tutorial, we will explain you how to merge two arrays without duplicate values in PHP. You can use the PHP array_unique() function and PHP array_merge() function together to merge two arrays into one array without duplicate values in PHP.

Merge two arrays

You can use PHP array_merge function for merging both arrays into one array. it’s giving output like this.

<?php
$array1 = array("yellow", "red", "green", "orange", "purple");
$array2 = array("pink", "brown", "green", "orange", "red");
$array  = array_merge($array1, $array2);
print_r($array);
?>
Array
(
    [0] => yellow
    [1] => red
    [2] => green
    [3] => orange
    [4] => purple
    [5] => pink
    [6] => brown
    [7] => green
    [8] => orange
    [9] => red
)

In above output you can see there are many duplicate entries But we want to remove these duplicate entries before merging both array.

Merge two arrays without duplicate values in PHP

Now we will use array_unique() and array_merge() both PHP function together to merge two arrays and remove duplicate values like in below example:

<?php
$array1 = array("yellow", "red", "green", "orange", "purple");
$array2 = array("pink", "brown", "green", "orange", "red");
$array = array_unique(array_merge($array1, $array2));
print_r($array);
?>
The above example will output:
Array
(
    [0] => yellow
    [1] => red
    [2] => green
    [3] => orange
    [4] => purple
    [5] => pink
    [6] => brown
)

In above output you can see we merged both arrays without duplicate values that’s what we want.

Leave A Reply

Your email address will not be published.