Given an unsorted array. How to find duplicates in array using PHP. These types of questions are generally asked in interviews. Sometimes interviewer allows to use in-built function sometimes not.
How to Find Duplicates in Array
Let’s assume the element of an array is 5,1,2,1,7,5 . To solve this problem i am using PHP in-built function array_count_values().
Top five most used array functions.
array_count_values() takes array as an argument and returns an array using the values of array as keys and their frequency in array as values.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 |
<?php $arr = array(5,1,2,1,7,5) ; /* Values and their count */ $arr_count = array_count_values($arr); print_r($arr_count); $res = array(); foreach($arr_count as $key=>$val){ /* If their occurrence is 1, it means it unique. */ if($val == 1){ $res[$key] = 'unique'; }else{ $res[$key] = 'duplicate'; } } print_r($res); ?> |
The output of the array you print.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
/* Values and their frequency count. */ Array ( [5] => 2 [1] => 2 [2] => 1 [7] => 1 ) /* Final array. */ Array ( [5] => duplicate [1] => duplicate [2] => unique [7] => unique ) |
You can use other optimized approach to make key and value pair as well. You can also find duplicates element in array without using in-built function in minimum time complexity.