In this post, we will see how to remove duplicates from an array in PHP. Two elements are considered equal if and only if the string representation is the same.

1. Removing duplicates using array_unique() function

The standard solution to remove duplicate values from an array is using the array_unique() function, which takes an array and returns a new array without duplicates and original order of keys preserved.

The following code demonstrates this:

Download  Run Code

 
For associative arrays, the key of the first equal element will be retained, as shown below:

Download  Run Code

 
For an array of different types, if the string representation of two elements is the same, the first element is used.

Download  Run Code

2. Find duplicates using array_diff_key() function

To find duplicates, you can use the array_diff_key() function which computes the difference of arrays using keys for comparison.

Download  Run Code

That’s all about removing duplicates from an array in PHP.