In the previous tutorial we talked about how we managed to get all the keys and values of an array using the arraykeys and arrayvalues method. This time around we are going to learn how to remove duplicate values in an array.This is useful if you are planning on filtering your array without having to do additional functions like if statements in getting unique values.
Array - The array you want to filter.
SortingType - (optional) Sort the array.
Getting the unique items is easy and all you have to do is use the arrayunique method.
<?php $animals = array('Cat','Cat','Dog','Mouse','Mouse','Zebra','Cow'); $unique_animals = array_unique($animals); echo var_dump($unique_animals); ?>
From the example above, it will return the animals that are unique which are "Cat","Dog","Mouse","Zebra" and "Cow". However, you have to take notice, that the arrayunique method is case sensitive. And will consider "CAT" and "Cat" as two different entities.
You can also sort them out using different sorting methods as follows.
SORTREGULAR - compare items normally (don't change types)
SORTNUMERIC - compare items numerically
SORTSTRING - compare items as strings
SORTLOCALESTRING - compare items as strings, based on the current locale.
Sorting them will easily make your code much neater and easy to read.