3.3 Eliminating Duplicate Elements


You want to extract unique items in an array, eliminating duplicate elements.

Technique

Use PHP's built-in array_unique() function:

 <?php $unique = array_unique ($duplicates); ?> 

Or, if you want to define uniqueness by an arbitrary criterion, loop through the array and see whether more than one element matches your criterion:

 <?php $n_array = array(); foreach ($array as $element) {     // Only three duplicate values are allowed     // in the new array.     if ($tstarray[$element] < 3) {         array_push ($n_array, $element);         $tstarray[$element]++;     } } ?> 

Comments

The array_unique() function will, given an array, strip the array of all its duplicate items and return a new array. The array_unique() function works on both associative and numerically indexed arrays.

If you want to be a little more specific than just checking whether an entry exists, you can write your own routine to search an array for what you define as duplicates. The basic idea of this is shown in the second example in the solution ”we search through $array and keep track of how many times each element of $array has been seen. If the element has been seen fewer than three times, we add it to our array; otherwise , we move to the next item.



PHP Developer's Cookbook
PHP Developers Cookbook (2nd Edition)
ISBN: 0672323257
EAN: 2147483647
Year: 2000
Pages: 351

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net