How to Remove Duplicate Elements from an Array in PHP

09/06/2021

Contents

In this article, you will learn how to remove duplicate elements from an array in PHP.

PHP array_unique() Function

In PHP, you can use the array_unique() function to remove duplicate elements from an array:

<?php
  $array = [1, 2, 3, 1, 2, 4];
  $unique_array = array_unique($array);

  print_r($unique_array);
?>

Output:

Array
(
    [0] => 1
    [1] => 2
    [2] => 3
    [5] => 4
)

The array_unique() function takes an array as input and returns a new array with all duplicate values removed. The returned array preserves the key-value associations of the original array, so if the original array had keys, the returned array will contain the same keys.

It should be noted that array_unique only works on simple data types, such as integers and strings. If the array contains more complex data types, such as objects, it may not work as expected. In those cases, you may need to implement a custom solution, for example by using a loop to iterate through the array and checking each value manually.

Here’s an example of using array_unique on an associative array:

<?php
  $array = [    "apple" => "red",    "banana" => "yellow",    "grape" => "purple",    "apple" => "green",];

  $unique_array = array_unique($array);

  print_r($unique_array);
?>

Output:

Array
(
    [apple] => green
    [banana] => yellow
    [grape] => purple
)