Thursday, October 16, 2025
HomeLanguagesHow to remove duplicate values from array using PHP ?

How to remove duplicate values from array using PHP ?

In this article, we will discuss how to remove duplicate elements from an array in PHP. We can get the unique elements by using array_unique() function. This function will remove the duplicate values from the array.

Syntax:

array array_unique($array, $sort_flags)

Note: The keys of the array are preserved i.e. the keys of the not removed elements of the input array will be the same in the output array.

Parameters: This function accepts two parameters that are discussed below:

  • $array: This parameter is mandatory to be supplied and it specifies the input array from which we want to remove duplicates.
  • $sort_flags: It is optional parameter. This parameter may be used to modify the sorting behavior using these values:
    • SORT_REGULAR: This is the default value of the parameter $sort_flags. This value tells the function to compare items normally (don’t change types).
    • SORT_NUMERIC: This value tells the function to compare items numerically.
    • SORT_STRING: This value tells the function to compare items as strings.
    • SORT_LOCALE_STRING: This value tells the function to compare items as strings, based on the current locale.

Return Value: The array_unique() function returns the filtered array after removing all duplicates from the array.

Example: PHP program to remove duplicate values from the array.

PHP




<?php
  
// Input Array
$a = array("red", "green", "red", "blue");
  
// Array after removing duplicates
print_r(array_unique($a));
  
?>


Output

Array
(
    [0] => red
    [1] => green
    [3] => blue
)

Example 2: PHP program to remove duplicate elements from an associative array.

PHP




<?php
  
// Input array
$arr = array(
      "a" => "MH", 
      "b" => "JK", 
      "c" => "JK", 
      "d" => "OR"
);
  
// Array after removing duplicates
print_r(array_unique($arr));
  
?>


Output

Array
(
    [a] => MH
    [b] => JK
    [d] => OR
)
RELATED ARTICLES

Most Popular

Dominic
32361 POSTS0 COMMENTS
Milvus
88 POSTS0 COMMENTS
Nango Kala
6728 POSTS0 COMMENTS
Nicole Veronica
11892 POSTS0 COMMENTS
Nokonwaba Nkukhwana
11954 POSTS0 COMMENTS
Shaida Kate Naidoo
6852 POSTS0 COMMENTS
Ted Musemwa
7113 POSTS0 COMMENTS
Thapelo Manthata
6805 POSTS0 COMMENTS
Umr Jansen
6801 POSTS0 COMMENTS