How to Make Each Element of an Array Unique in PHP


In this article, we show how to make each element of an array unique in PHP.

This means that if the array has multiple elements composed of the same exact item, we want to get rid of all the mulitiple values of the same thing and just have it listed in the array once.

In PHP, this can be done using the PHP array_unique() function.

This is shown in the code below.

This PHP array_unique() function gets rid of all multiple elements of the same thing and then just has it listed in the array once. This makes each element in the array unique.

So if you take an array and pass it through the PHP array_unique() function, it returns an array with only unique elements.

So let's say that we have the array below.

Bob Bob Diane Kelly John John Peter Bob

So you can see above all the duplicates in the array.

Bob is listed three times in the array. And John is listed twice in the array.

Now click the button below.

So now you can see that the array above is unique. No 2 elements have the exact same value.

This is the power of the PHP array_unique() function so that we don't return duplicate results of in an array if this is unwanted.

HTML Comment Box is loading comments...