Table of contents
1.
Introduction
2.
Definition and Usage  
3.
Syntax
4.
Parameters
5.
Return Value
6.
Example
6.1.
Example 1: Basic Usage of array_unique()
6.2.
Example 2: array_unique() with Associative Arrays
6.3.
Example 3: array_unique() with Different Sorting Types
7.
Important Points about array_unique() in PHP  
8.
Limitation of array_unique() in PHP  
9.
Frequently Asked Questions
9.1.
What happens to the keys when using array_unique()?
9.2.
How does array_unique() handle case-sensitive strings?
9.3.
Can array_unique() be used for multidimensional arrays?
10.
Conclusion
Last Updated: Feb 11, 2025
Easy

PHP array_unique() Function

Author Pallavi singh
0 upvote
Career growth poll
Do you think IIT Guwahati certified course can help you in your career?

Introduction

The PHP array_unique() function is used to remove duplicate values from an array, ensuring that each element appears only once. This function is useful for filtering out repeated values and organizing data efficiently. It works by comparing values and keeping only the first occurrence. 

PHP array_unique() Function

In this article, we will discuss the syntax, parameters, return value, and practical examples of array_unique() to help you understand how it works.

Definition and Usage  

The `array_unique()` function in PHP is used to remove duplicate values from an array. It takes an array as input & returns a new array where all the values are unique. This means if there are multiple occurrences of the same value in the original array, only the first occurrence will be kept, & the rest will be removed.  

To use this function, you simply pass the array you want to process as an argument. The syntax looks like this:  

<?php  
// Original array with duplicate values  
$numbers = [1, 2, 2, 3, 4, 4, 5];  

// Using array_unique() to remove duplicates  
$uniqueNumbers = array_unique($numbers);  

// Printing the result  
print_r($uniqueNumbers);  
?>
You can also try this code with Online PHP Compiler
Run Code


In this syntax:  

1. We start by creating an array called `$numbers` that contains some duplicate values.  

2. Next, we call the `array_unique()` function & pass `$numbers` as the argument.  

3. The function processes the array & removes the duplicates.  

4. Finally, we print the result using `print_r()`.  


When you run this code, the output will look like this:  

Output

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


Notice how the duplicate values (like `2` & `4`) are removed, but their original keys are preserved. This is an important behavior of `array_unique()` that we will discuss later.  

Syntax

The array_unique() function is used to remove duplicate values from an array. Below is the syntax:

array_unique(array, sorting_type)

Parameters

The array_unique() function accepts the following parameters:

  1. array (Required): The input array from which duplicate values need to be removed.
     
  2. sorting_type (Optional): This parameter determines how the array keys are compared. It has the following possible values:
    • SORT_STRING (Default) – Compares items as strings.
       
    • SORT_NUMERIC – Compares items as numbers.
       
    • SORT_REGULAR – Compares items normally without changing their types.
       
    • SORT_LOCALE_STRING – Compares items as strings, based on the current locale.

Return Value

The function returns a new array with duplicate values removed while maintaining the original order of the unique elements. The keys are preserved but may not be sequential.

Example

Let's look at an example where we remove duplicate values from an array:

Example 1: Basic Usage of array_unique()

<?php
$numbers = array(10, 20, 10, 30, 40, 50, 20, 30);
$unique_numbers = array_unique($numbers);
print_r($unique_numbers);
?>
You can also try this code with Online PHP Compiler
Run Code

 

Output:

Array
(
    [0] => 10
    [1] => 20
    [3] => 30
    [4] => 40
    [5] => 50
)

 

Explanation:

  • The duplicate values (10, 20, and 30) appear only once in the output array.
  • The original index keys are retained.

Example 2: array_unique() with Associative Arrays

<?php
$students = array(
    "A" => "John",
    "B" => "Alice",
    "C" => "John",
    "D" => "Mike"
);
$unique_students = array_unique($students);
print_r($unique_students);
?>
You can also try this code with Online PHP Compiler
Run Code

 

Output:

Array
(
    [A] => John
    [B] => Alice
    [D] => Mike
)

 

Explanation:

  • The duplicate value "John" is removed, and only the first occurrence is retained.
     
  • The keys are preserved as they were in the original array.

Example 3: array_unique() with Different Sorting Types

<?php
$values = array("100", 100, "200", 200, "300", 300);
$unique_values = array_unique($values, SORT_REGULAR);
print_r($unique_values);
?>
You can also try this code with Online PHP Compiler
Run Code

 

Output:

Array
(
    [0] => 100
    [2] => 200
    [4] => 300
)

 

Explanation:

  • Since we used SORT_REGULAR, it considers "100" and 100 as the same value and removes duplicates.
     
  • Similarly, "200" and 200, "300" and 300 are treated as duplicates and removed.

Important Points about array_unique() in PHP  

When you work with `array_unique()`, there are a few key points you need to keep in mind. These will help you use the function effectively & avoid unexpected results. Let’s discuss them one by one.  

1. Preserves Original Keys: The `array_unique()` function keeps the original keys of the array elements. This means that even after removing duplicates, the keys of the remaining elements stay the same. While this can be useful in some cases, it might cause confusion if you expect the keys to reset.  

Let’s take an example to show how keys are preserved:  

<?php  
// Array with duplicate values  
$fruits = ["a" => "apple", "b" => "banana", "c" => "apple", "d" => "orange"];  

// Using array_unique() to remove duplicates  
$uniqueFruits = array_unique($fruits);  

// Printing the result  
print_r($uniqueFruits);  
?>
You can also try this code with Online PHP Compiler
Run Code


In this Code:  

1. The `$fruits` array contains two occurrences of the value `"apple"`.  

2. After applying `array_unique()`, only the first occurrence of `"apple"` is kept, & its key (`"a"`) is preserved.  

3. The output will look like this:  

Array  
(  
    [a] => apple  
    [b] => banana  
    [d] => orange  
)  


2. Works with Both Indexed & Associative Arrays: The `array_unique()` function can handle both indexed arrays (arrays with numeric keys) & associative arrays (arrays with named keys). However, the behavior remains consistent—duplicate values are removed, & keys are preserved.  
 

3. Case-Sensitive Comparison: By default, `array_unique()` performs a case-sensitive comparison. This means that values like `"Apple"` & `"apple"` are treated as different. If you want to make the comparison case-insensitive, you’ll need to preprocess the array or use additional functions.  

Let’s discuss an example to discuss case sensitivity:  

<?php  
// Array with case-sensitive duplicates  
$items = ["Apple", "apple", "Banana", "banana", "APPLE"];  

// Using array_unique()  
$uniqueItems = array_unique($items);  

// Printing the result  
print_r($uniqueItems);  
?>
You can also try this code with Online PHP Compiler
Run Code


Output:  

Array  
(  
    [0] => Apple  
    [1] => apple  
    [2] => Banana  
    [3] => banana  
    [4] => APPLE  
)  


As you can see, all variations of `"Apple"` are treated as unique because the comparison is case-sensitive.  
 

4. Sorting Flags Can Be Used: PHP allows you to specify a sorting flag as the second argument in `array_unique()`. For example, you can use `SORT_STRING` to compare items as strings or `SORT_NUMERIC` to compare them as numbers. By default, PHP uses `SORT_STRING`.  

Example with sorting flags:  

<?php  
// Numeric array with duplicate values  
$numbers = [1, "1", 2, "2", 1];  

// Using array_unique() with SORT_NUMERIC  
$uniqueNumbers = array_unique($numbers, SORT_NUMERIC);  

// Printing the result  
print_r($uniqueNumbers);  
?>
You can also try this code with Online PHP Compiler
Run Code


Output:  

Array  
(  
    [0] => 1  
    [2] => 2  
)  


In this case, the numeric flag ensures that values like `1` & `"1"` are treated as the same.  

Limitation of array_unique() in PHP  

While `array_unique()` is a powerful function, it does have some limitations that you should be aware of. Understanding these limitations will help you use the function more effectively & avoid potential issues in your projects. Let’s discuss them in detail.  

1. Performance Issues with Large Arrays: One major limitation of `array_unique()` is that it can become slow when working with very large arrays. This happens because the function compares each element with every other element to identify duplicates. For small arrays, this isn’t a problem, but for arrays with thousands or millions of elements, the performance can degrade significantly.  

For example: 

<?php  
// Creating a large array with 100,000 elements  
$largeArray = array_fill(0, 100000, "value");  

// Adding a few unique values  
$largeArray[99998] = "unique1";  
$largeArray[99999] = "unique2";  

// Using array_unique() on the large array  
$start = microtime(true); // Start time  
$uniqueArray = array_unique($largeArray);  
$end = microtime(true); // End time  

// Printing the time taken  
echo "Time taken: " . ($end - $start) . " seconds";  
?>
You can also try this code with Online PHP Compiler
Run Code


In this Code:  

1. We create a large array with 100,000 elements, all having the same value (`"value"`).  
 

2. We add two unique values at the end of the array.  
 

3. We measure the time taken by `array_unique()` to process the array.  
 

When you run this code, you’ll notice that the function takes a noticeable amount of time to complete. For extremely large datasets, this can become a bottleneck.  
 

2. Limited Support for Multi-Dimensional Arrays: Another limitation is that `array_unique()` doesn’t work directly with multi-dimensional arrays. If you pass a multi-dimensional array to the function, it won’t remove duplicates from nested arrays. Instead, it treats each sub-array as a single value, which means duplicates within sub-arrays are ignored.  

For example:  

<?php 
// Multi-dimensional array with duplicates  
$multiArray = [  
    ["apple", "banana"],  
    ["apple", "banana"],  
    ["orange"]  
];  

// Using array_unique()  
$uniqueMultiArray = array_unique($multiArray);  


// Printing the result  
print_r($uniqueMultiArray);  
?>
You can also try this code with Online PHP Compiler
Run Code


Output:  

Notice: Array to string conversion in...


As you can see, PHP throws a notice because `array_unique()` cannot handle multi-dimensional arrays. To work around this, you would need to write custom logic to process nested arrays.  
 

3. Case-Sensitivity Can Be a Problem: As mentioned earlier, `array_unique()` performs case-sensitive comparisons by default. While this behavior is useful in some cases, it can cause issues if you want to treat `"Apple"` & `"apple"` as the same value. Unfortunately, there’s no built-in way to make the function case-insensitive—you’ll need to preprocess the array manually.  

Example of case-sensitivity issue:  

<?php  
// Array with case-sensitive duplicates  
$items = ["Apple", "apple", "APPLE"];  

// Using array_unique()  
$uniqueItems = array_unique($items);  

// Printing the result  
print_r($uniqueItems);  
?>
You can also try this code with Online PHP Compiler
Run Code


Output:  

Array  
(  
    [0] => Apple  
    [1] => apple  
    [2] => APPLE  
)  


All variations of `"Apple"` are treated as unique, which might not be the desired behavior.  
 

4. Cannot Handle Complex Data Types: The `array_unique()` function works well with simple data types like strings & numbers, but it struggles with complex data types like objects or resources. If you try to use it on an array containing objects, it won’t behave as expected because PHP doesn’t know how to compare objects directly.  

Frequently Asked Questions

What happens to the keys when using array_unique()?

The original array keys are preserved but may become non-sequential. Use array_values() to re-index them.

How does array_unique() handle case-sensitive strings?

It treats uppercase and lowercase letters as different values, meaning "Alice" and "alice" are considered unique.

Can array_unique() be used for multidimensional arrays?

No, it only works on single-dimensional arrays. A custom function is needed for multidimensional arrays.

Conclusion

In this article, we learned about the PHP array_unique() function and how it helps remove duplicate values from an array. We also explored different ways to generate random numbers in PHP using functions like rand(), mt_rand(), and random_int(). Understanding these functions allows developers to handle arrays efficiently and generate random values securely in PHP applications.

Live masterclass