Guest User

removeDuplicates()

a guest
Feb 22nd, 2012
352
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. <?php
  2.     /**
  3.     * Removes values from an array if they are shown more than once
  4.     *
  5.     * @param array $arr
  6.     * @return array
  7.     */
  8.     function removeDuplicates($arr) {
  9.         if (!is_array($arr)) { // Error handling
  10.             return $arr;
  11.         }
  12.        
  13.         // Temporary array with every value found
  14.         $tempArr = array();
  15.        
  16.         foreach ($arr AS $key => $val) {
  17.             if (isset($tempArr[$val])) { // If value is already found...
  18.                 // ... unset the first key found and the actual key...
  19.                 unset($arr[$tempArr[$val]], $arr[$key]);
  20.             } else { // ... otherwise, mark this value as found
  21.                 $tempArr[$val] = $key;
  22.             }
  23.         }
  24.        
  25.         // Return array with rearranged keys
  26.         return array_values($arr);
  27.     }
  28.  
  29.     // --------------------
  30.     // Set up test environment
  31.     $size = 100000; // Size of array to remove duplicates from
  32.     $diversity = 10000; // number of different values in test array
  33.    
  34.     // Fill array with random numeric values
  35.     $array = array();
  36.     for ($i = 0; $i < $size; $i++) {
  37.         $array[] = rand(0,$diversity);
  38.     }
  39.    
  40.     // --------------------
  41.     // Start test
  42.  
  43.     $start = microtime(true);
  44.    
  45.     removeDuplicates($array);
  46.    
  47.     var_dump(microtime(true) - $start);
RAW Paste Data