To deduplicate array elements, we generally use the array_unique method. This method can deduplicate the elements in the array.
Output:
Array( [0] => 1 [1] => 2 [2] => 3 [3] => 4 [4] => 5 [5] => 6 [6] => 7 [7] => 8 [8] => 9)
After deduplication, the key values will be out of order. You can use array_values to reorder the key values.
';echo 'run time:'.(float)(($endtime-$starttime)*1000).'ms
';echo 'use memory:'.getUseMemory();/** * 获取使用内存 * @return float */function getUseMemory(){ $use_memory = round(memory_get_usage(true)/1024,2).'kb'; return $use_memory; }/** * 获取microtime * @return float */function getMicrotime(){ list($usec, $sec) = explode(' ', microtime()); return (float)$usec + (float)$sec; }?>
unique count:99
run time:653.39303016663ms
use memory:5120kb
Use thearray_uniquemethod to remove duplicates. The running time takes about650msand the memory usage is about5m
php has a key-value exchange method array_flip. We can use this method to deduplicate. Because of key-value exchange, the original duplicate values will become the same key.
Then perform a key-value exchange and exchange the keys and values back to complete deduplication.
';echo 'run time:'.(float)(($endtime-$starttime)*1000).'ms
';echo 'use memory:'.getUseMemory();/** * 获取使用内存 * @return float */function getUseMemory(){ $use_memory = round(memory_get_usage(true)/1024,2).'kb'; return $use_memory; }/** * 获取microtime * @return float */function getMicrotime(){ list($usec, $sec) = explode(' ', microtime()); return (float)$usec + (float)$sec; }?>
unique count:99
run time:12.840032577515ms
use memory:768kb
Usearray_flipmethod to remove duplicates, the running time takes about18ms, the memory usage is about2m
. Therefore, using thearray_flipmethod to remove duplicates takes longer than using thearray_uniquemethod. The running time is98%, memory usage reduced4/5;
This article explains how to achieve the rapid deduplication effect of PHP array elements. For more related content, please pay attention to the PHP Chinese website.
Related recommendations:
How to find array elements through php to improve efficiency
About mysql strict mode Strict Mode Explanation
#php uses explode to split strings. Explanation of issues that novices easily overlook
The above is the detailed content of How to achieve quick deduplication effect of php array elements. For more information, please follow other related articles on the PHP Chinese website!