Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <?php
- /**
- * Removes values from an array if they are shown more than once
- *
- * @param array $arr
- * @return array
- */
- function removeDuplicates($arr) {
- if (!is_array($arr)) { // Error handling
- return $arr;
- }
- // Temporary array with every value found
- $tempArr = array();
- foreach ($arr AS $key => $val) {
- if (isset($tempArr[$val])) { // If value is already found...
- // ... unset the first key found and the actual key...
- unset($arr[$tempArr[$val]], $arr[$key]);
- } else { // ... otherwise, mark this value as found
- $tempArr[$val] = $key;
- }
- }
- // Return array with rearranged keys
- return array_values($arr);
- }
- // --------------------
- // Set up test environment
- $size = 100000; // Size of array to remove duplicates from
- $diversity = 10000; // number of different values in test array
- // Fill array with random numeric values
- $array = array();
- for ($i = 0; $i < $size; $i++) {
- $array[] = rand(0,$diversity);
- }
- // --------------------
- // Start test
- $start = microtime(true);
- removeDuplicates($array);
- var_dump(microtime(true) - $start);
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement