Remove duplicate values from array, show only unique values in Php

March 3rd, 2023

Remove duplicates in php with array_unique(). Now you get only unique values in array - no duplicates.

1$cities = ['Rio', 'London', 'London', 'Rome', 'NY']
2 
3$uniqueCities = array_unique($cities) // ['Rio', 'London', 'Rome', 'NY']

If you want to find duplicates and then count them, use array_diff_key() and array_count_values():

1$duplicateCities = array_diff_key($cities, $uniqueCities) // [London]
2 
3array_count_values($duplicateCities); // 1