In this short guide, I will show you how to remove duplicate elements from an array in PHP. In this tutorial, we will use PHP’s array_unique function.
Let’s take a look at the following example:
//An example array containing duplicate strings.
$example = array('dog', 'cat', 'horse', 'cat', 'dog');
//var_dump the array to view its contents.
//use the array_unique function to remove duplicates.
$example = array_unique($example);
//var_dump the filtered array to view its contents.
In the code above, we created a simple example array of strings – with each string representing a type of animal. In this array, there are duplicates of both “dog” and “cat”.
If you var_dump the array above, you will see that its structure looks like this:
However, if you pass the array into the function array_unique, you will find that the returned value will end up looking like this:
As you can see, the strings “cat” and “dog” were both removed from the end of the array.
This brings me to my next point: The array_unique function will leave the first occurrence and remove any subsequent duplicates. i.e. It will skip over the first element before removing any duplicates that come after it.
It is also worth noting that the array keys / indexes are preserved. For example, if you add the string “bird” onto the end of the example array above, you will find that array_unique will leave its index / key as “5”, even though there are only 4 elements left in the array.