W3docs

Understanding func_array_unique in PHP

Learn how to remove duplicate values from PHP arrays using array_unique. Covers syntax, sort flags, and practical examples.

In this article, we will discuss the PHP function array_unique. This function removes duplicate values from an array. It returns an array containing only the unique values, preserving the original keys of the first occurrences. The original array remains unchanged.

Syntax

The syntax of array_unique is:

PHP array_unique Syntax

array array_unique ( array $array [, int $sort_flags = SORT_STRING ] )

array: The input array to filter

sort_flags: The optional sorting flags that determine how comparisons are performed. The default is SORT_STRING. Other common options include SORT_REGULAR (compare normally without type conversion), SORT_NUMERIC (compare numerically), and SORT_NATURAL (compare as strings using "natural ordering").

Examples

Here are some examples of using array_unique.

Example 1

The following example removes the duplicates from the given array:

PHP removes the duplicates from the given array by using array_unique function

php— editable, runs on the server

Output:

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

Example 2

The following example removes the duplicates from the given associative array:

PHP removes the duplicates from the given associative array by using array_unique

php— editable, runs on the server

Output:

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

Conclusion

In conclusion, array_unique is a useful PHP function that can remove duplicates from an array. Its syntax is straightforward, and it is easy to use. We hope that this article has been helpful to you in understanding array_unique. If you have any questions or comments, please feel free to leave them below.

Practice

Practice
What does the array_unique function in PHP do?
What does the array_unique function in PHP do?
Was this page helpful?