remove duplicate values from a PHP array

How to remove duplicate values from a PHP array?

PHP array_unique() function to remove duplicates

PHP has a built-in array function called array_unique() that collects all unique values from the given array, and returns an array of those unique values. There is no loss of keys in the returned array.

array_unique(array, FLAG optional);
<?php
$fruits = [
    "Apple",
    "Banana",
    "Watermelon",
    "Apple",
    "Grapes",
    "Banana",
    "Mango"
];

$uniqueFruits = array_unique($fruits);

print_r($uniqueFruits);
Array
(
    [0] => Apple
    [1] => Banana
    [2] => Watermelon
    [4] => Grapes
    [6] => Mango
)

Remove duplicate values from a multidimensional array

There is not functions in PHP that can remove duplicate values from a multidimensional array.

To achieve this we will use the following trick –

  • First we will serialize the internal arrays. It helps to convert the multidimensional array to one dimensional array.
  • Then we can use the array_unique() function.
  • And at the end, we have to unserialize the unique array.

To follow the above steps first you must know about some PHP built-in functions – array_map(), serialize() and unserialize().

<?php
$data = [
    "fruits" => ["Apple", "Banana", "Mango"],
    "vagetables" => ["Potato", "Tomato", "Pumpkin"],
    "fruits2" => ["Apple", "Banana", "Mango"],
    "crops" => ["Rice", "Wheat", "Barley"]
];

// Serializing the internal values
$serialized = array_map('serialize', $data);

// Removing duplicates
$removed = array_unique($serialized);

// Unserializing the internal values
$unserialized = array_map('unserialize', $removed);

print_r($unserialized);

/**
 * -- One Liner --
 * $inOneLine = array_map('unserialize', array_unique(array_map('serialize', $data)));
 * print_r($inOneLine);
 * 
 */
Array
(
    [fruits] => Array
        (
            [0] => Apple
            [1] => Banana
            [2] => Mango
        )

    [vagetables] => Array
        (
            [0] => Potato
            [1] => Tomato
            [2] => Pumpkin
        )

    [crops] => Array
        (
            [0] => Rice
            [1] => Wheat
            [2] => Barley
        )

)

Note: the above trick will not work if

The above trick will not work if the order of the internal array values are not same.

$data = [
    "fruits" => ["Apple", "Banana", "Mango"],
    "fruits2" => ["Mango", "Apple", "Banana"],
];