Count distinct elements in an array | PHP program to count all distinct elements in a given array ; First sort the array so that all occurrences become consecutive ; Traverse the sorted array ; Move the index ahead while there are duplicates ; Driver Code
< ? php function countDistinct ( $ arr , $ n ) { sort ( $ arr , 0 ) ; $ res = 0 ; for ( $ i = 0 ; $ i < $ n ; $ i ++ ) { while ( $ i < $ n - 1 && $ arr [ $ i ] == $ arr [ $ i + 1 ] ) $ i ++ ; $ res ++ ; } return $ res ; } $ arr = array ( 6 , 10 , 5 , 4 , 9 , 120 , 4 , 6 , 10 ) ; $ n = sizeof ( $ arr ) ; echo countDistinct ( $ arr , $ n ) ; ? >