Home > Articles

chap3_0672323257

  • Print
  • + Share This

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.

  • + Share This
  • 🔖 Save To Your Account

Related Resources

There are currently no related titles. Please check back later.