Php array element deduplication
1. remove duplicates using the array_unique method
To deduplicate array elements, we usually use the array_unique method. this method can be used to deduplicate the elements in the array.
123456
Output:
Array( [0] => 1 [1] => 2 [2] => 3 [3] => 4 [4] => 5 [5] => 6 [6] => 7 [7] => 8 [8] => 9)123456789101112
After deduplication, the key values are not sorted in order. you can use array_values to re-sort the key values.
2. de-duplication efficiency using the array_unique method
'; Echo 'run time:'. (float) ($ endtime-$ starttime) * 1000). 'Ms
'; Echo 'use memory :'. getUseMemory ();/*** get memory usage * @ return float */function getUseMemory () {$ use_memory = round (memory_get_usage (true)/, 2 ). 'KB'; return $ use_memory;}/*** get microtime * @ return float */function getMicrotime () {list ($ usec, $ sec) = explode ('', microtime (); return (float) $ usec + (float) $ sec;}?> 1234567891011121314151617181920212223242526272829303132333435363738394041
Unique count: 99
Run time: 653.39303016663 ms
Use memory: 5120kb
The array_unique method is used to remove duplicates. the running time is about 650 ms, and the memory usage is about 5 m.
3. faster array deduplication method
Php has a key-value interchange method, array_flip. we can use this method to remove duplicates. because of key-value swaps, the original duplicate values will become the same key.
Then perform another key-value swap. you can replace the key and value to complete deduplication.
'; Echo 'run time:'. (float) ($ endtime-$ starttime) * 1000). 'Ms
'; Echo 'use memory :'. getUseMemory ();/*** get memory usage * @ return float */function getUseMemory () {$ use_memory = round (memory_get_usage (true)/, 2 ). 'KB'; return $ use_memory;}/*** get microtime * @ return float */function getMicrotime () {list ($ usec, $ sec) = explode ('', microtime (); return (float) $ usec + (float) $ sec;}?> 123456789101112131415161718192021222324252627282930313233343536373839404142
Unique count: 99
Run time: 12.840032577515 ms
Use memory: 768kb
The array_flip method is used to remove duplicates. the running time is about 18 ms, and the memory usage is about 2 m.
Therefore, the array_flip method is less than the array_unique method, and the memory usage is reduced by 98%;