In this guide, we are going to show you how to remove duplicate values from a PHP array.
In the example below, we will be using PHP’s array_unique function.
Take a look at the following code:
//An example array containing duplicate values. $example = array('dog', 'cat', 'horse', 'cat', 'dog'); //var_dump the array to view its contents. var_dump($example); //use the array_unique function to remove duplicates. $example = array_unique($example); //var_dump the filtered array to view its contents. var_dump($example);
In the snippet above, we created a simple array of strings.
Each value represents a type of animal.
However, there is one problem here: We have duplicates of both “dog” and “cat”.
If you print out the array above, you will see that its structure looks like this:
When you pass it into the array_unique function, you will see that the function returns the following structure:
As you can see, the function has automatically removed the duplicate “cat” and “dog” values.
This brings us to our next point.
The array_unique function will keep the first occurrence and remove any subsequent duplicates. In other words, will skip over the first element and then remove any identical elements that come after it.
It is also worth noting that it will preserve the array keys.
For example, if you add the string “bird” to the end of the array, it will have the key “5”.
This is despite the fact that “3” and “4” no longer exist.