- Chapter 3: Using Arrays
- 1 Declaring an Array
- 2 Printing Out an Array
- 3 Eliminating Duplicate Elements
- 4 Enlarging or Shrinking an Array
- 5 Merging Arrays
- 6 Iteratively Processing Elements in an Array
- 7 Accessing the Current Element in an Array
- 8 Accessing Different Areas of an Array
- 9 Searching an Array
- 10 Searching for the Different Elements in Two Arrays
- 11 Randomizing the Elements of an Array
- 12 Determining the Union, Intersection, or Difference Between Two Arrays
- 13 Sorting an Array
- 14 Sorting Sensibly
- 15 Reversing Order
- 16 Perl-Based Array Manipulation Features
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 solutionwe 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.