PHP
downloads | documentation | faq | getting help | mailing lists | reporting bugs | php.net sites | links | conferences | my php.net

search for in the

array_unshift> <array_uintersect
Last updated: Fri, 16 May 2008

view this page in

array_unique

(PHP 4 >= 4.0.1, PHP 5)

array_unique β€” Removes duplicate values from an array

Description

array array_unique ( array $array )

Takes an input array and returns a new array without duplicate values.

Note that keys are preserved. array_unique() sorts the values treated as string at first, then will keep the first key encountered for every value, and ignore all following keys. It does not mean that the key of the first related value from the unsorted array will be kept.

Note: Two elements are considered equal if and only if (string) $elem1 === (string) $elem2. In words: when the string representation is the same. The first element will be used.

Parameters

array

The input array.

Return Values

Returns the filtered array.

Examples

Example #1 array_unique() example

<?php
$input 
= array("a" => "green""red""b" => "green""blue""red");
$result array_unique($input);
print_r($result);
?>

The above example will output:

Array
(
    [a] => green
    [0] => red
    [1] => blue
)

Example #2 array_unique() and types

<?php
$input 
= array(4"4""3"43"3");
$result array_unique($input);
var_dump($result);
?>

The above example will output:

array(2) {
  [0] => int(4)
  [2] => string(1) "3"
}



array_unshift> <array_uintersect
Last updated: Fri, 16 May 2008
 
add a note add a note User Contributed Notes
array_unique
PHP Expert
14-Apr-2008 05:34
case insensitive for PHP v4.x and up.

<?php

function in_iarray($str, $a){
foreach(
$a as $v){
if(
strcasecmp($str, $v)==0){return true;}
}
return
false;
}

function
array_iunique($a){
$n = array();
foreach(
$a as $k=>$v){
if(!
in_iarray($v, $n)){$n[$k]=$v;}
}
return
$n;
}

$input = array("aAa","bBb","cCc","AaA","ccC","ccc","CCC","bBB","AAA","XXX");
$result = array_iunique($input);
print_r($result);

/*
Array
(
    [0] => aAa
    [1] => bBb
    [2] => cCc
    [9] => XXX
)
*/
?>
xp_sim at hotmail dot com
10-Mar-2008 05:55
Ray dot Paseur at SometimesUsesGmail dot com :

You might also want to try array_count_values. This function returns the number of repetitions for each value in the array.

Then, you sort the resulting array in descending order and parse it using a "foreach" to get all the values that are present more than once in the original array.

Ex. :

<?php

//From your code
$raw_array     = array();
$raw_array[1]    = 'abc@xyz.com';
$raw_array[2]    = 'def@xyz.com';
$raw_array[3]    = 'ghi@xyz.com';
$raw_array[4]    = 'abc@xyz.com'; // Duplicate

//Count the no. of repetitions
$count_by_value = array_count_values( $raw_array );

//Sort in asc. order
natcasesort( $count_by_value )

//Reverse order (desc.)
$count_desc = array_reverse( $count_by_value );

$not_uniques = array();

foreach(
$count_desc as $orignal_value => $count){

   
//Exit loop if only uniques remain
   
if( $count == 1 ){ break; }
   
   
//Add current value to the output array
   
$not_uniques[] = $orignal_value;
}

print_r($not_uniques);
?>

What do you think ?
Ray dot Paseur at SometimesUsesGmail dot com
01-Mar-2008 07:46
I needed to identify email addresses in a data table that were replicated, so I wrote the array_not_unique() function:

<?php

function array_not_unique($raw_array) {
   
$dupes = array();
   
natcasesort($raw_array);
   
reset ($raw_array);

   
$old_key    = NULL;
   
$old_value    = NULL;
    foreach (
$raw_array as $key => $value) {
        if (
$value === NULL) { continue; }
        if (
$old_value == $value) {
           
$dupes[$old_key]    = $old_value;
           
$dupes[$key]        = $value;
        }
       
$old_value    = $value;
       
$old_key    = $key;
    }
return
$dupes;
}

$raw_array     = array();
$raw_array[1]    = 'abc@xyz.com';
$raw_array[2]    = 'def@xyz.com';
$raw_array[3]    = 'ghi@xyz.com';
$raw_array[4]    = 'abc@xyz.com'; // Duplicate

$common_stuff    = array_not_unique($raw_array);
var_dump($common_stuff);
?>
php_array_unique [at] peterwarnock.com
19-Dec-2007 11:20
To clarify the note above Example #1, the function appears to cast the elements to strings for comparison and then return the type of the first unique element encountered. 

<?php
$input
= array(0, 2, "2", 3, "9", 9);
$result = array_unique($input);
var_dump($result);
?>

array(4) {
  [0]=>
  int(0)
  [1]=>
  int(2)
  [3]=>
  int(3)
  [4]=>
  string(1) "9"
}
mnbayazit
28-Oct-2007 03:18
case insensitive

<?php
function array_iunique($array) {
    return
array_intersect_key($array,array_unique(
                
array_map(strtolower,$array)));
}
?>
array_unique_FULL
11-Oct-2007 12:58
<?php
function array_unique_FULL($array) {
  foreach(
$array as $k => $v) {
    if (
is_array($v)) {
     
$ret = array_unique_FULL(array_merge($ret, $v));
    } else {
     
$ret[$k] = $v;
    }
  }
//for

 
return array_unique($ret);
}
?>

Array
(
    [0] => js/pt.js
    [1] => js/selectfile.js
    [2] => js/pt.js
    [3] => js/proyecto.js
    [4] => Array
        (
            [0] => Array
                (
                    [0] => js/selectfile.js
                    [1] => js/selectfile.js
                    [2] => js/y otro mas.js
                )

            [1] => q se yo
        )

)

go array_unique_FULL()!!!!

Array
(
    [0] => js/pt.js
    [1] => js/selectfile.js
    [3] => js/proyecto.js
    [6] => js/y otro mas.js
    [5] => q se yo
)
mew at world dot end dot org
02-Oct-2007 12:05
Smaller version for PHP5

<?php

# array array_unique_save (array array [, bool preserve_keys] )
function array_unique_save ($a, $pk = true) {
   
$a = array_diff_key($a, array_unique($a));
    return (
$pk ? $a : array_values($a));
}

?>
logicearth at gmail dot com
16-Sep-2007 04:57
Should have thought of this sooner. x.x

<?php

function array_unique_save_php4 ($a, $pk = true) {
   
$t = array_keys(array_unique($a));
    foreach (
$t as $k) { unset($a[$k]); }
    return (
$pk ? $a : array_values($a));
}

?>
xjazey at hotmail dot com
11-Sep-2007 11:50
This is a solution to remove duplicate values from an array

<?php

$array
[0] = "Yellow";
$array[1] = "Green";
$array[2] = "Yellow";
$array[3] = "Blue";
$array[4] = "Yellow";

$array = array_keys(array_flip($array));

//$array will output Yellow Green Blue

?>
tsikano at attglobal dot net
21-Aug-2007 04:20
Suggestion for being able to use array_unique on array of arrays/objects:

<?php
foreach ($arrayOfArrays as $key=>$value) {
 
$arrayOfArrays[$key] = "'" . serialize($value) . "'";
}
$arrayOfArrays = array_unique($arrayOfArrays);
foreach (
$arrayOfArrays as $key=>$value) {
 
$arrayOfArrays[$key] = unserialize(trim($value, "'"));
}
?>
webmaster at jukkis dot net
30-Jul-2007 04:08
Another way to 'unique column' an array, in this case an array of objects:
Keep the desired unique column values in a static array inside the callback function for array_filter.

Example:
<?php
/* example object */
class myObj {
  public
$id;
  public
$value;
  function
__construct( $id, $value ) {
   
$this->id = $id;
   
$this->value = $value;
  }
}

/* callback function */
function uniquecol( $obj ) {
  static
$idlist = array();

  if (
in_array( $obj->id, $idlist ) )
    return
false;

 
$idlist[] = $obj->id;
  return
true;   
}

/* a couple of arrays with second array having an element with same id as the first */
$list  = array( new myObj( 1, ), new myObj( 2, 100 ) );
$list2 = array( new myObj( 1, 10 ), new myObj( 3, 100 ) );
$list3 = array_merge( $list, $list2 );

$unique = array_filter( $list3, 'uniquecol' );
print_r( $list3 );
print_r( $unique );

?>

In addition, use array_merge( $unique ) to reindex.
snoyes+php at gmail dot com
11-Jul-2007 09:08
Another way to get unique objects/arrays:
<?php
function my_array_unique($array) {
    return
array_intersect_key($array, array_unique(array_map('serialize', $array)));
}
?>
jmw at petriweb dot org
05-Jun-2007 04:33
The intersection won't work, since:
  intersection (['a','a','b','c'] , UNIQUE(['a','a','b','c']) )
=
  intersection (['a','a','b','c'], ['a','b','c'])
=
  ['a','a','b','c']

While you only want ['a'] or ['a','a'] to be the result. The only solution is to write your own function.
kosi at designsbykosi dot info
04-Jun-2007 07:20
to n@cho: $dup_values = array_intersect($array, array_unique($array));

I took the intersection instead of the difference.
laurynas dot butkus at gmail dot com
23-May-2007 04:22
This one would work with objects and arrays also.

<?php
function my_array_unique($array, $keep_key_assoc = false)
{
   
$duplicate_keys = array();
   
$tmp         = array();       

    foreach (
$array as $key=>$val)
    {
       
// convert objects to arrays, in_array() does not support objects
       
if (is_object($val))
           
$val = (array)$val;

        if (!
in_array($val, $tmp))
           
$tmp[] = $val;
        else
           
$duplicate_keys[] = $key;
    }

    foreach (
$duplicate_keys as $key)
        unset(
$array[$key]);
       
    return
$keep_key_assoc ? $array : array_values($array);
}
?>
danny at lostsockdesign dot com dot au
12-Apr-2007 06:44
An updated version of webcreators script that fixes a notice error about an undefined index and removes blank array value.

<?php
function my_array_unique($from) {
    for (
$i=count($from)-1;$i>1;$i--) {
       
$last = $from[$i];
       
$from[$i] = false;
        if (!
in_array($last,$from)) {
           
$from[$i]=$last;  
        }
    }
   
$from = array_unique($from);
   
$from = array_slice($from,0,count($from)-1);
    return
$from;
}
?>
n@cho NOSPAM cofrepuntonet
13-Dec-2006 02:45
What if I only want the duplicated items, not the unique ones?

I tried to do it by using array_diff of an array and its unique, but it did not work (any help?); so I made this function with a relatively good efficiency:

<?php
function array_repeated($array) {

    if(!
is_array($array)) return false;
   
$repeated_values = Array();
   
$array_unique = array_unique($array);
    if(
count($array)-count($array_unique)) {
        for(
$i=0;$i<count($array);$i++) {
            if(!
array_key_exists($i, $array_unique)) $repeated_values[] = $array[$i];
        }
    }
    return
$repeated_values;
}
?>

This function is based on the behaviour of the array_unique function that mantains the indexes of the array when deleting the item.
n@cho NOSPAM cofrepuntonet
13-Dec-2006 02:26
Note that array_unique preserves the keys, even if the array is not associative:

$values = Array("john@hotmail.com", "peter@hotmail.com", "will@hotmail.com", "john@hotmail.com", "laura@hotmail.com", "mariah@hotmail.com");
echo "<br>".count($values)." values.<br>";
var_dump($values);

$unique_values = array_unique($values);
echo "<br>".count($unique_values)." unique values.<br>";
var_dump($unique_values);

RESULT:

6 values.
array(6) {
  [0]=>
  string(16) "john@hotmail.com"
  [1]=>
  string(17) "peter@hotmail.com"
  [2]=>
  string(16) "will@hotmail.com"
  [3]=>
  string(16) "john@hotmail.com"
  [4]=>
  string(17) "laura@hotmail.com"
  [5]=>
  string(18) "mariah@hotmail.com"
}

5 unique values.
array(5) {
  [0]=>
  string(16) "john@hotmail.com"
  [1]=>
  string(17) "peter@hotmail.com"
  [2]=>
  string(16) "will@hotmail.com"
  [4]=>
  string(17) "laura@hotmail.com"
  [5]=>
  string(18) "mariah@hotmail.com"
}

$unique_values[3] is missing. Use array_merge or array_values if you need the index to be linear.
arr1
01-Nov-2006 08:59
Just to note that array_unique, treats null values as none unique values. So if your using array_unique to detect duplicate values it will also detect multiple null values.
Ome_Henk
27-Oct-2006 12:16
For people looking at the flip flip method for getting unique values in a simple array. This is the absolute fastest method:

$unique = array_keys(array_flip($array));

It's marginally faster as $unique = array_merge(array_flip(array_flip($array)));

And it's marginally slower as $unique array_flip(array_flip($array)) which leaves gaps.

It's still about twice as fast or fast as array_unique.

This tested on several different machines with 100000 random arrays. All machines used a version of PHP5.
geuis dot teses at gmail dot com
09-Oct-2006 10:27
Here's the shortest line of code I could find/create to remove all duplicate entries from an array and then reindex the keys.

//$var is an array. This example its one-dimensional. Your most basic kind of array.

$var = array_values(array_unique($var));
geuis dot teses at gmail dot com
09-Oct-2006 09:53
Sorry to repost this but it was helpful and took a while to find all the way down.

Ric
05-Apr-2005 09:44
A very simple way of getting rid of duplicate entries and re-indexing with key starting at 0:

   $temp=array_unique($main);
   $main=array_values($temp);
keneks at gmail dot com
30-Sep-2006 07:01
Taking the advantage of array_unique, here is a simple function to check if an array has duplicate values.

It simply compares the number of elements between the original array and the array_uniqued array.

function array_search_dups($array)
{
    $dup_array = $array;
    $dup_array = array_unique($dup_array);
    if(count($dup_array) != count($array))
    {
        return TRUE;
    }
    else
    {
        return FALSE;
    }
}
pulsarkowy at NOSPAM dot gmail dot com
13-Sep-2006 04:30
This function below will remove multiple values from array, remove 'empty' fields an also count how many times the given value occured.

it's rather slow and not 'elegant' but works.
usage:

$myarray=my_array_unique($myarray)

in return it produces an 3 fields array:
1st is index number, 2nd is the value, 3rd is counter.

function my_array_unique($tablica)
{

$tnum=count($tablica);
$i=1;
$k=1;
$t[1]['product']="";
$t[1]['count']=1;
while($i<=$tnum) {
  if (!array_multi_search($tablica[$i], $t)) {
    $t[$k]['product']=$tablica[$i];
    $t[$k]['count']=1;
    $k++;
  }
  else {
    $y=1;
    while ($y<=count($t)) {
      if ($t[$y]['product']==$tablica[$i])
        $t[$y]['count']++;
      $y++;
    }

  }
 
$i++;


$tablica=$t;
return $tablica;
};

the function uses another function that i've found on the php.net site (i'm posting it only for informational reasons - i can't remember who wrote it):

function array_multi_search( $p_needle, $p_haystack )
   {
       if( !is_array( $p_haystack ) )
       {
           return false;
       }

       if( in_array( $p_needle, $p_haystack ) )
       {
           return true;
       }

       foreach( $p_haystack as $row )
       {
           if( array_multi_search( $p_needle, $row ) )
           {
               return true;
           }
       }

       return false;
   }
jacob dot bates at gmail dot com
16-Aug-2006 03:25
In response to muddmonkey's flip-flip method, i would like to note that using this method as-is leaves the array with gaps.  For example, if we have an array like this:

Array
(
    [0] => 1
    [1] => 1
    [2] => 1
)

And you apply the flip-flip method, you get this:

Array
(
    [2] => 1
)

If you apply the array_merge function to the result, it closes these gaps without seriously sacrificing performance.  I wrote some test code that would result in a unique array that has 10,000 elements so that the impact of array_merge was more evident.  Here is my test code:

function microtime_float(){ //timing (stolen from muddmonkey)
   list($usec, $sec) = explode(" ", microtime());
   return ((float)$usec + (float)$sec);
}
//make an array and fill it up
$final=array();
for($i=0;$i<50000;$i++){
   $final[]=$i%10000; //make sure the unique array has 10000 elements
}
//try flip-flip
$start1 = microtime_float();
array_flip(array_flip($final));
$stop1=microtime_float();
echo($stop1-$start1.' (flip-flip)<br>');
//try my flip-flip-merge
$start2=microtime_float();
array_merge(array_flip(array_flip($final)));
$stop2=microtime_float();
echo($stop2-$start2.' (flip-flip-merge)<br />');
//try array_unique
$start3=microtime_float();
array_unique($final);
$stop3=microtime_float();
echo($stop3-$start3.' (array_unique)<br />');

Here was the result:
0.14240193367004 (flip-flip)
0.18947601318359 (flip-flip-merge)
3.7108051776886 (array_unique)

As you can see, flip-flip-merge slows it down a little, but both are still way faster than array_unique.
KoKos
03-Aug-2006 02:27
In response to muddmonkey@harveyMcoldotedu (yeah, i know i'm a bit too late :D )

In your example you're using the "flip-flip" AFTER doing the array_unique() already. That's why it is so fast. ;)
a dot fotoglidis at 7mbit dot net
23-Jul-2006 08:25
In addition to brettz9's remove_dups:

This one will actually take a multi-dimensional array and return it minus the duplicates in regard to the specified element of the inner arrays.

<?php
/*
  Initialising new array to the first element of the given array.
  Check whether current element in initial array has already been added to new array.
  If yes break to save us some time. If no, then add current element to new array.
*/

function remove_dups($array, $row_element) {   
   
$new_array[0] = $array[0];
    foreach (
$array as $current) {
       
$add_flag = 1;
        foreach (
$new_array as $tmp) {
            if (
$current[$row_element]==$tmp[$row_element]) {
               
$add_flag = 0; break;
            }
        }
        if (
$add_flag) $new_array[] = $current;
    }
    return
$new_array;
}
// end function remove_dups
?>

______________________________________________
EXAMPLE

<?php
    $array
[0] = array('Charles','Wade',233);
   
$array[1] = array('Charles','Watson',234);
   
$array[2] = array('Tom','Wade',235);
   
$array = remove_dups($array,0);
?>

The above example will output:
Array
(
    [0] => Array ([0] => 'Charles' [1] => 'Wade' [2] => 233)
    [1] => Array ([0] => 'Tom' [1] => 'Wade' [2] => 235)
)

<?php
remove dups
($array,1);
?>

will output:
Array
(
    [0] => Array ([0] => 'Charles' [1] => 'Wade' [2] => 233)
    [1] => Array ([1] => 'Charles' [1] => 'Watson' [2] => 234)
)

At each case it removes all inner arrays that have a duplicate in the specified position and keeps the first inner array only.
uditsawhney at yahoo dot com
15-Jul-2006 12:14
<?php

//Fn for array_unique column-wise for multi-dimensioanl array without losing keys | Start
function array_uniquecolumn($arr)
{
   
$rows   = sizeof($arr);
   
$columns = sizeof($arr[0]);
   
   
$columnkeys = array_keys($arr[0]);
   

    for(
$i=0; $i<$columns; $i++)
    {
        for(
$j=0;$j<$rows;$j++)
        {
            for(
$k = $j+1; $k<$rows; $k++)
            {
                if(
$arr[$j][$columnkeys[$i]] == $arr[$k][$columnkeys[$i]])
                   
$arr[$k][$columnkeys[$i]] = "";       
            }
        }
   
    }

return (
$arr);

}
//Fn for array_unique column-wise for multi-dimensioanl array without losing keys | Stop

$arrUGCourse[]= array(  "CTR" => "1",

                       
"UGCOURSE"=>"ABC",

                       
"TSINITIATE"=>"540",

                       
"COUNT"=>"34",

                       
"ENTRY_DT"=>"2006-05-01",

                       
"CUMULATIVE"=> 44);

 

$arrUGCourse[]= array(  "CTR" => "2",

                       
"UGCOURSE"=>"ABC",

                       
"TSINITIATE"=>"5401",

                       
"COUNT"=>"341",

                       
"ENTRY_DT"=>"2006-05-11",

                       
"CUMULATIVE"=> 44);

print_r(array_uniquecolumn($arrUGCourse));

?>
davin at baragiotta dot org
19-Apr-2006 03:52
I used the code submitted by "agarcia" regarding multi-dimensional arrays but keys with no data were still there. I've just added a line to completely unset the redondant part of the array so it is now acting like array_unique.

<?php
function remove_dup($matriz) {
  
$aux_ini=array();
  
$entrega=array();
   for(
$n=0;$n<count($matriz);$n++) {
     
$aux_ini[]=serialize($matriz[$n]);
   }
  
$mat=array_unique($aux_ini);
   for(
$n=0;$n<count($matriz);$n++) {
     
$entrega[]=unserialize($mat[$n]);
   }
   foreach (
$entrega as $key => $row){
      if (!
is_array($row)) { unset($entrega[$key]); }
   }
   return
$entrega;
}
?>

Thanks!

Davin Baragiotta
MoD
14-Apr-2006 09:02
The shortest way i found to remove duplicate array from a column,
For example if you parse Multiple XML sources, you can remove duplicate items that contain the same link.

<?PHP
function        remove_duplicate($array, $field)
{
  foreach (
$array as $sub)
   
$cmp[] = $sub[$field];
 
$unique = array_unique($cmp);
  foreach (
$unique as $k => $rien)
   
$new[] = $array[$k];
  return
$new;
}
?>
agarcia at rsn dot com dot co
31-Mar-2006 12:41
This is a script for multi_dimensional arrays
function remove_dup($matriz) {
    $aux_ini=array();
    $entrega=array();
    for($n=0;$n<count($matriz);$n++)
    {
        $aux_ini[]=serialize($matriz[$n]);
    }
    $mat=array_unique($aux_ini);
    for($n=0;$n<count($matriz);$n++)
    {
       
            $entrega[]=unserialize($mat[$n]);
       
    }
    return $entrega;
}
brettz9
09-Mar-2006 12:51
If you have a multi-dimensional array and wish to remove duplicates from a particular "column" as well as the corresponding values in the other "columns", you might find the following helpful.

<?php
function remove_dups($array, $index) {
   
$array_count = count($array);
   
$array_count_inner = count($array[$index]);
    for (
$i=0; $i<$array_count_inner; $i++) {
        for (
$j=$i+1; $j<$array_count_inner; $j++) {
            if (
$array[$index][$i]==$array[$index][$j]) {
                for (
$k=0; $k<$array_count; $k++) {
                    unset(
$array[$k][$i]);
                }
// end for   
           
} // end if
       
} // end for   
   
} // end for
   
return $array;
}
// end function remove_dups
?>
mcmeijer at yahoo dot com
27-Jan-2006 05:18
This is a recursive arrayUnique function for arrays of any dimension. (tested with 4-dimensional array)
The line '$newArray=deleteEmpty($newArray);' is optional and removes empty keys and values
<?php
function arrayUnique($myArray)
    {
   
$newArray = Array();
    if (
is_array($myArray))
        {
        foreach(
$myArray as $key=>$val)
            {
            if (
is_array($val))
                {
               
$val2 = arrayUnique($val);
                }
            else
                {
               
$val2 = $val;
               
$newArray=array_unique($myArray);
               
$newArray=deleteEmpty($newArray);
                break;
                }
            if (!empty(
$val2))
                {
               
$newArray[$key] = $val2;
                }
            }
        }
    return (
$newArray);
    }

function
deleteEmpty($myArray)
    {
   
$retArray= Array();
    foreach(
$myArray as $key=>$val)
        {
        if ((
$key<>"") && ($val<>""))
            {
           
$retArray[$key] = $val;
            }
        }
    return
$retArray;
    }
?>
memandeemail at gmail dot com
03-Jan-2006 10:47
Problem:
I have loaded an array with the results of a database
query.  The Fields are 'FirstName' and 'LastName'.

I would like to find a way to contactenate the two
fields, and then return only unique values for the
array.  For example, if the database query returns
three instances of a record with the FirstName John
and the LastName Smith in two distinct fields, I would
like to build a new array that would contain all the
original fields, but with John Smith in it only once.
Thanks for: Colin Campbell

Solution:

/**
 * The same thing than implode function, but return the keys so
 *
 * <code>
 * $_GET = array('id' => '4587','with' => 'key');
 * ...
 * echo shared::implode_with_key('&',$_GET,'='); // Resultado: id=4587&with=key
 * ...
 * </code>
 *
 * @param string $glue Oque colocar entre as chave => valor
 * @param array $pieces Valores
 * @param string $hifen Separar chave da array do valor
 * @return string
 * @author memandeemail at gmail dot com
 */
function implode_with_key($glue = null, $pieces, $hifen = ',') {
  $return = null;
  foreach ($pieces as $tk => $tv) $return .= $glue.$tk.$hifen.$tv;
  return substr($return,1);
}

/**
 * Return unique values from a tree of values
 *
 * @param array $array_tree
 * @return array
 * @author memandeemail at gmail dot com
 */
function array_unique_tree($array_tree) {
  $will_return = array(); $vtemp = array();
  foreach ($array_tree as $tkey => $tvalue) $vtemp[$tkey] = implode_with_key('&',$tvalue,'=');
  foreach (array_keys(array_unique($vtemp)) as $tvalue) $will_return[$tvalue] = $array_tree[$tvalue];
  return $will_return;
}

$problem = array_fill(0,3,
array('FirstName' => 'John', 'LastName' => 'Smith')
);

$problem[] = array('FirstName' => 'Davi', 'LastName' => 'S. Mesquita');
$problem[] = array('FirstName' => 'John', 'LastName' => 'Tom');

print_r($problem);

print_r(array_unique_tree($problem));
webcreator at centrum dot cz
28-Oct-2005 04:25
array_unique function starts its comparation from beginning and pop the key off if there is more values inside array. The last one remains. But i needed to hold priority of the order of values and let the first one in.

Here is my easy solution:
##---

function my_array_unique($from)
{
for ($i=count($from);$i>1;$i--)
    {
    $last = $from[$i];
    $from[$i] = "";
    if (!in_array($last,$from))
        $from[$i]=$last;   
    }
return array_unique($from);
}

# One empty value remains in array.
# But its very easy to separate it while using output array.
kenrbnsn at rbnsn dot com
26-Sep-2005 09:09
Yet another Array_Unique for multi-demensioned arrays. I've only tested this on two-demensioned arrays, but it could probably be generalized for more, or made to use recursion.

This function uses the serialize, array_unique, and unserialize functions to do the work.

<?php
function multi_unique($array) {
    foreach (
$array as $k=>$na)
       
$new[$k] = serialize($na);
   
$uniq = array_unique($new);
    foreach(
$uniq as $k=>$ser)
       
$new1[$k] = unserialize($ser);
    return (
$new1);
}
?>
passtschu AT freenet DOT de
21-Sep-2005 07:20
array_unique for multidimensional arrays. similar to the DISTINCT in SQL function.
the function can group, sum and count keys

<?PHP
/*
$array - nothing to say
$group_keys - columns which have to be grouped - can be STRING or ARRAY (STRING, STRING[, ...])
$sum_keys - columns which have to be summed - can be STRING or ARRAY (STRING, STRING[, ...])
$count_key - must be STRING - count the grouped keys
*/
function array_distinct ($array, $group_keys, $sum_keys = NULL, $count_key = NULL){
  if (!
is_array ($group_keys)) $group_keys = array ($group_keys);
  if (!
is_array ($sum_keys)) $sum_keys = array ($sum_keys);

 
$existing_sub_keys = array ();
 
$output = array ();

  foreach (
$array as $key => $sub_array){
   
$puffer = NULL;
   
#group keys
   
foreach ($group_keys as $group_key){
     
$puffer .= $sub_array[$group_key];
    }
   
$puffer = serialize ($puffer);
    if (!
in_array ($puffer, $existing_sub_keys)){
     
$existing_sub_keys[$key] = $puffer;
     
$output[$key] = $sub_array;
    }
    else{
     
$puffer = array_search ($puffer, $existing_sub_keys);
     
#sum keys
     
foreach ($sum_keys as $sum_key){
        if (
is_string ($sum_key)) $output[$puffer][$sum_key] += $sub_array[$sum_key];
      }
     
#count grouped keys
     
if (!array_key_exists ($count_key, $output[$puffer])) $output[$puffer][$count_key] = 1;
      if (
is_string ($count_key)) $output[$puffer][$count_key]++;
    }
  }
  return
$output;
}
?>
muddmonkey@harveyMcoldotedu
17-Aug-2005 01:44
If you're doing numeric arrays etc. I found flip-flip to work much better than array_unique:

<?PHP
   
function microtime_float(){ //timing
      
list($usec, $sec) = explode(" ", microtime());
       return ((float)
$usec + (float)$sec);
    }

   
//make an arry and fill it up
   
$final=array();
    for(
$i=0;$i<50000;$i++){
       
$final[]=$i%13; //make sure there are some dupes
   
}
   
//try array unique
   
$start1 = microtime_float();
   
array_unique($final);
   
$stop1=microtime_float();
    echo(
$stop1-$start1.'<br>');
   
//try my flip-flip
   
$start2=microtime_float();
   
array_flip(array_flip($final));
   
$stop2=microtime_float();
    echo(
$stop2-$start2);
?>

Running this with only ints in the array (as above) I get runtimes such as:
1.6195669174194 (using unique)
0.017037868499756 (using flip flip)
which is two orders of magnitude faster!

Appending a string:
($final[]='test'.$i%13;)
gives:
0.42909598350525 (using unique)
0.023258924484253 (using flip-flip)
Which is not AS great, but still 20x faster than unique.

In both cases the flip-flip seems to use less memory than the unique.

Granted the flip-flip doesn't work for all cases, but if you're doing simple stuff like this, the flip-flip will give you better run times.

~JF
Christoph Ziegenberg
17-Jun-2005 11:44
If the array key is a string it might be important to keep it although the value is the same (as I need it at the moment). So I wrote a function which also returns array elements which have the same value but different string keys.

function array_unique_numeric ($arr)
{
    $str = $int = array();
    foreach(array_keys($arr) as $key) {
        ${(is_int($key)?'int':'str')}[$key] = $arr[$key];
    }
    return array_merge($str, array_unique($int));
}

// typical array after an array_merge()...
$array = array("a" => "green", "b" => "brown", "c" => "blue", "red", "d" => "green", "yellow", "red");

print_r(array_unique($array));
// Array
// (
//     [a] => green
//     [b] => brown
//     [c] => blue
//     [0] => red
//     [1] => yellow
// )

print_r(array_unique_numeric($array));
// Array
// (
//     [a] => green
//     [b] => brown
//     [c] => blue
//     [d] => green
//     [0] => red
//     [1] => yellow
// )
memandeemail at gmail dot com
15-Apr-2005 01:46
/**
 * Removes duplicate keys from an array
 *
 * @param array $array
 * @return array
 */
function array_unique_key($array) {
    $result = array();
    foreach (array_unique(array_keys($array)) as $tvalue) {
        $result[$tvalue] = $array[$tvalue];
    }
    return $result;
}
Ric
05-Apr-2005 09:44
A very simple way of getting rid of duplicate entries and re-indexing with key starting at 0:

    $temp=array_unique($main);
    $main=array_values($temp);
trigger at e-mail dot ru
03-Feb-2005 02:53
Just a simple implementation for JavaScript:
function array_unique(thearray)
{
    thearray.sort();
    //reset($thearray);
    newarray = new Array();
    for (n=0;n<thearray.length;n++)
    {
        unique=1;//by default
        for(nn=0;nn<newarray.length;nn++)
            if (thearray[n] == newarray[nn])
            {
                unique=0;//already exists
                break;
            }
        if(unique)//dont exists
            newarray.push(thearray[n]);
    }
    return newarray;
 }
lucas.bickel AT purplehaze DOT ch
26-Oct-2004 08:39
I quite like the following code for making multidimensional arrays unique:

foreach ($arrAddressList AS $key => $arrAddress) {
    $arrAddressList[$key] = serialize($arrAddress);
}
$arrAddressList = array_unique($arrAdressList);
foreach ($arrAddressList AS $key => $strAddress) {
    $arrAddressList[$key] = unserialize($strAddress);
}

This gets me a unique array while not minding wether the the original array contains arrays or just strings (or whatever...).
Vary
07-Oct-2004 01:24
This script will unique the array and count the times appearance.

find more information at http://php.scmtv.com/
justin at redwiredesign dot com
14-Sep-2004 06:23
OK, so here's my version that maintains index integrity:

function array_unique($array)
{
    $out = array();
   
    //    loop through the inbound
    foreach ($array as $key=>$value) {
        //    if the item isn't in the array
        if (!in_array($value, $out)) {
            //    add it to the array
            $out[$key] = $value;
        }
    }
   
    return $out;
}
wernerlistas at terra dot com dot br
16-Jun-2004 08:50
Following the code copies of a little function I've wrote that actually works with multidimensional arrays.
It also resets the array indexes.

<?php
if ( !function_exists( "arrayUnique" ) ){
    function
arrayUnique ( $rArray ){
       
$rReturn = array ();
        while ( list(
$key, $val ) = each ( $rArray ) ){
            if ( !
in_array( $val, $rReturn ) )
           
array_push( $rReturn, $val );
        }
        return
$rReturn;
    }
}
?>
csaba at alum dot mit dot edu
09-Jun-2004 07:17
The following is an efficient, adaptable implementation of array_unique which always retains the first key having a given value:

<?php
function array_unique2(&$aray) {
   
$aHash = array();
    foreach (
$aray as $key => &$val) if (@$aHash[$val]++) unset ($aray[$key]);
}
?>

It is also adaptable to multi dimensional arrays.  For example, if your array is a sequence of (multidimensional) points, then in place of @$aHash[$val]++ you could use @$aHash[implode("X",$val)]++
If you want to not have holes in your array, you can do an array_merge($aray) at the end.

Csaba Gabor
patrikG at home dot net
11-Mar-2004 07:05
If you need to have the keys of the duplicates in an array returned, you may find this function useful:

<?php
function unique_events($array){
   
//checks $array for duplicate values and returns an
        //array containing the keys of duplicates
   
$count= array_intersect_assoc($array, array_flip( array_count_values($array)));
    foreach(
$array as $key=>$value){
        if (
in_array($value,$count)){
           
$return[$value][]=$key;
        }
    }
    return
$return;
}
?>

Example:

Input:
Array
(
    [0] => 44
    [1] => 23
    [2] => 23
    [3] => 23
    [4] => 9
    [5] => 9
    [6] => 9
    [7] => 9
    [8] => 9
    [9] => 9
    [10] => 9
    [11] => 9
)

Function returns:
Array
(
    [23] => Array
        (
            [0] => 1
            [1] => 2
            [2] => 3
        )

    [9] => Array
        (
            [0] => 4
            [1] => 5
            [2] => 6
            [3] => 7
            [4] => 8
            [5] => 9
            [6] => 10
            [7] => 11
        )

)
bitmore.co.kr
19-Feb-2004 03:53
//Modify
Object Unique

<?php
   
class foo {
        var
$_name;
        var
$_age;
        function
foo($name,$age=NULL)    { $this->_name = $name; $this->_age = $age; }
       
//function get()        { return $this->_name; }
        //function set($name,$age=NULL)    { $this->_name = $name; $this->_age = $age; }
   
}

    function
DistinctOn ($obj, $item) {
       
$out = array();
       
$list = array();
        foreach (
$obj as $key=>$so) {
            if (!
in_array($so->$item, $list)) {
                echo
"key = $key,so = $so,item = $item,IFlist = ";print_r($list);echo "<br>";
               
$list[] = $so->$item;//°ΛΑυΉθΏ­
               
$out[$key] = $so;
            }
            echo
"Forlist = ";print_r($list);echo "<br>";
     &