Zend - The PHP Company




Arrays

Add Code


array_rm_dupes  

Type: code fragment
Added by: vbodrov
Entered: 01/04/2002
Last modified: 04/12/2001
Rating: - (fewer than 3 votes)
Views: 4107
Description: array array_rm_dupes(array array, [boolean is_sorted]) array_rm_dupes() removes duplicate values from an array. It takes input array and returns a new array without duplicate values. array_rm_dupes() sorts the input array in case if is_sorted flag is "false" (default). Two elements are considered equal if and only if (string) $elem1 === (string) $elem2 NOTE THAT UNLIKE THE STANDARD array_unique() FUNCTION KEYS ARE PRESERVED!


<?
 
/*************************************************************************
  *  array_rm_dupes routine v.1.00
  *  Language: PHP4
  *  Author:   Vadim Bodrov (falkoris@hotmail.com)
  *  Date:     2 April 2002
  *
  *  Description:
  *    array array_rm_dupes(array array, [boolean is_sorted])
  *
  *  array_rm_dupes() removes duplicate values from an array. It takes
  *  input array and returns a new array without duplicate values.
  *  array_rm_dupes() sorts the input array in case if is_sorted flag is
  *  "false" (default). Two elements are considered equal if and only if
  *  (string) $elem1 === (string) $elem2
  *
  *  NOTE THAT UNLIKE THE STANDARD array_unique() FUNCTION KEYS ARE
  *  PRESERVED!
  *************************************************************************/
 
  
function array_rm_dupes($arg_array$is_sorted false)
  {
    if (!
$is_sorted)
      
sort($arg_array);
    if (
count($arg_array) > 1)
    {
      
$res = array($last $arg_array[0]);
      for (
$i 1$i count($arg_array); $i++)
      {
        if (!((string) 
$arg_array[$i] === (string) $last))
        {
          
array_push($res$arg_array[$i]);
          
$last $arg_array[$i];
        }
      }
      return 
$res;
    } else
      return 
$arg_array;
  }
?>


Usage Example


<?
  $a 
= array ("green""blue""blue""white""yellow""green""magenta");
  
sort($a);
  echo 
"<b>Initial array:</b><br>";
  for (
$i 0$i count($a); $i++)
    echo 
"[$a[$i]] ";
  
$a array_rm_dupes($a);
  echo 
"<br><br><b>Processed array:</b><br>";
  for (
$i 0$i count($a); $i++)
    echo 
"[$a[$i]] ";
?>


Rate This Script





Search



This Category All Categories