SSISO Community

시소당

배열 함수 - array_unique ( array array)

array_unique
(PHP  4  >=  4.0.1,  PHP  5)

array_unique  --  배열에서  중복된  값을  제거한다
설명
array  array_unique  (  array  array)


array_unique()는  입력  array를  취해서  중복값이  없는  새로운  배열을  반환한다.  

키는  보존된다는  것에  유의한다.  array_unique()는  우선  문자열로  취급되는  값들을  정렬하고,  모든  값중  첫번째로  만나는  키를  보유하게  될것이고,  다음의  모든  키들은  무시될것이다.  이  말의  의미는  정렬되지  않은  array  의  첫번째  관련  값의  키가  유지된다는  것이  아니다.  

참고:  두  구성요소가  동치라고  볼수  있는  때는  (string)  $elem1  ===  (string)  $elem2  일때  만이다.  In  words:  when  the  string  representation  is  the  same.  

첫번째  원소가  사용될것이다.  

예  1.  array_unique()  예제코드

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

위  코드의  결과는  다음과  같다:  

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


예  2.  array_unique()  과  타입

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

위  스크립트의  결과는  다음과  같다:  

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





  add  a  note  User  Contributed  Notes
array_unique  
Christoph  Ziegenberg
17-Jun-2005  02: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
//  )  
cdblog  at  gmail  dot  com
20-May-2005  03:59  
<?php
/**
*  @param  string
*  @return  array
*  @author  Cocol
*  @desc  generate  unique  keywords
*  for  more  detail  please  visit  http://php.clickz.cn/articles/array/array_unique.html
*/
function  keyword_unique($url  =  "")  {
      $unique  =    array(
              'words'  =>  array(),
              'times'  =>  array(),
      );        
      
      $buffer  =  @file_get_contents($url);
      $words1  =  str_word_count(strtolower(strip_tags($buffer)),1);        
      $unique['words']  =  array_unique($words1);
      foreach  ($words1  as  $key=>$val)  {                
              if  (!in_array($val,$unique['words']))  {                        
                      $unique['times'][]  =  1;
              }  else  {
                      $i  =  array_search($val,$unique['words']);
                      $unique['times'][$i]  +=  1;
              }
      }
      array_multisort($unique['times'],SORT_DESC,$unique['words']);
      return  $unique;
}

$keywords  =  keyword_unique("http://php.clickz.cn/");
print_r($keywords);

?>  
memandeemail  at  gmail  dot  com
15-Apr-2005  04: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  12: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  05: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  11: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  04: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  09: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  11: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  10: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  10: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  06: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;//?&#705;??  
                              $out[$key]  =  $so;  
                      }  
                      echo  "Forlist  =  ";print_r($list);echo  "<br>";  
              }  
              return  $out;  
      }  

      $foo_obj[0]  =  new  foo('tom',20);  
      $foo_obj[1]  =  new  foo('paul',66);  
      $foo_obj[2]  =  new  foo('tom',23);  

      $item  =  '_name';  
      $result  =  DistinctOn  ($foo_obj,  $item);  

      while(list($k,$v)  =  each($result))  {  
              print  "K  =  ";print_r($k);  
              print  ",V  =  ";print_r($v);  
              print  "<br>";  
      }  
      //key  =  0,so  =  Object,item  =  _name,IFlist  =  Array  (  )  ,Forlist  =  Array  (  [0]  =>  tom  )  
      //key  =  1,so  =  Object,item  =  _name,IFlist  =  Array  (  [0]  =>  tom  )  ,Forlist  =  Array  (  [0]  =>  tom  [1]  =>  paul  )  
      //Forlist  =  Array  (  [0]  =>  tom  [1]  =>  paul  )  
      //K  =  0,V  =  foo  Object  (  [_name]  =>  tom  [_age]  =>  20  )  
      //K  =  1,V  =  foo  Object  (  [_name]  =>  paul  [_age]  =>  66  )  

      print  "<br><br>";  
      $item  =  '_age';  
      $result  =  DistinctOn  ($foo_obj,  $item);  
      while(list($k,$v)  =  each($result))  {  
              print  "K  =  ";print_r($k);  
              print  ",V  =  ";print_r($v);  
              print  "<br>";  
      }  

      //key  =  0,so  =  Object,item  =  _age,IFlist  =  Array  (  )  ,Forlist  =  Array  (  [0]  =>  20  )  
      //key  =  1,so  =  Object,item  =  _age,IFlist  =  Array  (  [0]  =>  20  )  ,Forlist  =  Array  (  [0]  =>  20  [1]  =>  66  )  
      //key  =  2,so  =  Object,item  =  _age,IFlist  =  Array  (  [0]  =>  20  [1]  =>  66  )  ,  
      //        Forlist  =  Array  (  [0]  =>  20  [1]  =>  66  [2]  =>  23  )  
      //K  =  0,V  =  foo  Object  (  [_name]  =>  tom  [_age]  =>  20  )  
      //K  =  1,V  =  foo  Object  (  [_name]  =>  paul  [_age]  =>  66  )  
      //K  =  2,V  =  foo  Object  (  [_name]  =>  tom  [_age]  =>  23  )  
?>  
matt  at  remove_mehsmx  dot  com
17-Feb-2004  07:57  
Note  that  
<?php
array_unique($anyarray);
?>
does  not  do  anything,  unlike  other  array  functions  such  as  
<?php
sort($anyarray);
?>
You  have  to  use  something  like:
<?php
$anyarray  =  array_unique($anyarray);
?>  
14-Jan-2004  08:23  
this  simple  function  is  similar  based  on  to  the  function  unique_multi_array  posted  by  tru  at  ascribedata  dot  com,  but  will  work  for  objects  rather  than  arrays.  use  2d  objects.  Its  eg  useful  to  work  with  mysql  queries  since  in  recent  versions,  the  DISTINCT  option  in  mysql  selects  will  only  work  when  selecting  a  single  (not  more)  row.  

eg.  
foo_obj[0]:    name:  'tom',  age:  '20'  
foo_obj[1]:    name:  'paul',  age:  '66'  
foo_obj[2]:    name:  'tom',  age:  '23'  

foo_obj  =  DistinctOn  ($foo_obj,  $item)  will  return  

foo_obj[0]:    name:  'tom',  age:  '20'  
foo_obj[1]:    name:  'paul',  age:  '66'  

<?php  
function  DistinctOn  ($obj,  $item)  {  
      $out  =  array();  
      $list  =  array();  
      foreach  ($obj  as  $key=>$so)  {  
              if  (!in_array($so->$item,  $list))  {  
                      $list[]  =  $so->$item;  
                      $out[$key]  =  $so;  
              }  
      }  
      return  $out;  
}  
?>  
tru  at  ascribedata  dot  com
16-Oct-2003  07:40  
Here's  a  function  to  make  a  multi-dimensional  array  have  only  DISTINCT  values  for  a  certain  "column".  It's  like  using  the  DISTINCT  parameter  on  a  SELECT  sql  statement.  

<?php  
function  unique_multi_array($array,  $sub_key)  {  
      $target  =  array();  
      $existing_sub_key_values  =  array();  
      foreach  ($array  as  $key=>$sub_array)  {  
              if  (!in_array($sub_array[$sub_key],  $existing_sub_key_values))  {  
                      $existing_sub_key_values[]  =  $sub_array[$sub_key];  
                      $target[$key]  =  $sub_array;  
              }  
      }  
      return  $target;  
}  
?>  
kay_rules  at  yahoo  dot  com
24-May-2003  05:28  
this  function  will  return  an  array  with  unique  value  and  proper  key  increment  start  from  0.  

<?php  
/*******************************/  
function  my_array_unique($somearray){  
      $tmparr  =  array_unique($somearray);  
      $i=0;  
      foreach  ($tmparr  as  $v)  {  
              $newarr[$i]  =  $v;  
              $i++;  
      }  
      return  $newarr;  
}  
/********************************/  
?>  

eg:  

<?php  
$foo_arr[0]  ='aa'  
$foo_arr[1]  ='bb'  
$foo_arr[2]  ='cc'  
$foo_arr[3]  ='bb'  
$foo_arr[4]  ='aa'  
$foo_arr[5]  ='dd'  
?>  

normal  array_unique  will  return:  

<?php  
$foo_arr[0]  ='aa';  
$foo_arr[1]  ='bb';  
$foo_arr[2]  ='cc';  
$foo_arr[3]  ='';  
$foo_arr[4]  ='';  
$foo_arr[5]  ='dd'  
?>  

my_array_unique  will  return:  

<?php  
$foo_arr[0]  ='aa';  
$foo_arr[1]  ='bb';  
$foo_arr[2]  ='cc';  
$foo_arr[3]  ='dd'  
?>  
martin  at  lucas-smith  dot  co  dot  uk
27-Jan-2003  08:12  
To  get  a  list  of  the  duplicated  values  in  an  array,  array_unique  isn't  much  help.  Instead,  use  array_filter  in  conjunction  with  a  callback  function,  as  below:  

<?php  
$checkKeysUniqueComparison  =  create_function('$value','if  ($value  >  1)  return  true;');  
$result  =  array_keys  (array_filter  (array_count_values($array),  $checkKeysUniqueComparison));  
?>  

These  two  lines  therefore  will  create  $result,  an  array  of  duplicated  values  in  the  array  $array,  once  each.  E.g.  the  array  
$array  =  array  ("a",  "b",  "a",  "b",  "x",  "y",  "z",  "x");  
gives  the  result  
Array([0]  =>  a  [1]  =>  b  [2]  =>  x)  
juggler  at  webworkerinfo  dot  de
10-Jan-2003  08:20  
in  addition  to  bisqwit:  
in  some  cases  you  can  simply  use  serialize  instead  of  recursivemakehash().  

<?php  
function  array_unique2($input)  {  
      $tmp  =  array();  
      foreach($input  as  $a  =>  $b)  
              $tmp[$a]  =  serialize($b);  
      $newinput  =  array();  
      foreach(array_unique($tmp)  as  $a  =>  $b)  
              $newinput[$a]  =  $input[$a];  
      return  $newinput;  
}  
?>  

Have  fun  
Juggler  
deigo  at  swirve  dot  NOSPAM  dot  com
23-Sep-2002  01:04  
Before  I  found  the  mysql  distinct  I  had  to  make  a  nicer  array  from  the  keys/values  that  I  got  from  array_unique  so.
$groups=array_unique($groups);
$newgroup[0]=reset($groups);
for  ($x=1;$x<sizeof($groups);$x++)
{
$newgroup[$x]=next($groups);
}  
php  at  hp-site  dot  dk
29-Aug-2002  02:15  
Try  this:
array_flip(array_flip($array));

It  gives  the  same  result  as  the  old  array_unique()  
29-Aug-2002  05:39  
<?  
$truc  =  array("l810u00","l810u00","l810q00");  
$machin  =  array_unique($truc);  
for($i=0;$i  <  count($machin)  ;  $i++){  
print  $machin[$i]."
";  
}  
?>  
result  :  
l810u00  

This  is  not  strange:  $machin  (as  returned  by  array  unique),  contains  "l810u00"  either  in  key[0]  or  key[1]  but  not  both  (the  key  depends  on  the  ersion  of  PHP),  and  "l810q00"  in  key[2].
The  returned  array  has  TWO  elements  so  count($machin)==2.
The  returned  array  has  a  hole  in  it,  and  you're  not  displaying  its  full  content.  You  could  verify  it  by  using  this  display  loop  instead:
foreach($machine  as  $key=>$value){  
print  '['  .  $key  .  ']  =>  '  .  $value  .  '
";  
}  
result:
[0]  =>  l810q00
[2]  =>  l810u00
(the  first  line  may  display  [1]  instead  of  [0]  for  PHP  4.0.1p3,  but  you'll  get  the  same  order  of  values  and  two  lines,  as  expected).  When  calling  array_values()  on  the  result,  you're  building  a  new  array  with  the  same  values  in  the  same  order,  but  with  renumbered  keys  (without  holes  in  numeric  keys).  
bisqwit  at  iki  dot  fi
25-May-2002  11:32  
The  recursivemakehash()  in  my  previous  post  contained  a  flaw.  Adding  md5()  to  "return  $tab;"  fixes  it  making  it  now  possible  to  distinguish  array(0=>'x')  from  'F4DBDF218CDC1683'  etc.  
bisqwit  at  iki  dot  fi
24-May-2002  12:36  
array_unique()  doesn't  return  anything  useful  if  your  input  is  an  
array  containing  arrays.  This  function  overcomes  the  problem.  
Any  level  of  recursions  is  possible  here.  If  the  input  is  a  plain  
array,  the  result  is  compatible  with  array_unique()  result.  

<?php  
function  recursivemakehash($tab)  
{  
    if(!is_array($tab))  
      return  $tab;  
    $p  =  '';  
    foreach($tab  as  $a  =>  $b)  
      $p  .=  sprintf('%08X%08X',  crc32($a),  crc32(recursivemakehash($b)));  
    return  $p;  
}  
function  array_unique2($input)  
{  
    $dumdum  =  array();  
    foreach($input  as  $a  =>  $b)  
      $dumdum[$a]  =  recursivemakehash($b);  
    $newinput  =  array();  
    foreach(array_unique($dumdum)  as  $a  =>  $b)  
      $newinput[$a]  =  $input[$a];  
    return  $newinput;  
}  
?>  
spunk  at  dasspunk  dot  NOSPAM  dot  com
14-Nov-2001  07:52  
I  needed  a  way  of  retaining  the  original  array's  keys  in  the  new,  unique  array.  I  came  up  with  this.  It  works  for  my  purposes  but  may  need  refinement.  

function  my_array_unique($somearray)  
{  
      asort($somearray);  
      reset($somearray);  
      $currentarrayvar  =  current($somearray);  
      foreach  ($somearray  as  $key=>$var)  
      {  
              if  (next($somearray)  !=  $currentarrayvar)  
              {  
                      $uniquearray[$key]  =  $currentarrayvar;  
                      $currentarrayvar  =  current($somearray);  
              }  
      }  
      reset($uniquearray);  
      return  $uniquearray;  
}  
ailanto  at  kafejo  dot  com
24-Aug-2001  12:04  
As  in  4.0.3pl1,  array_unique()  in  4.0.5  returns  the  *last*  key  encountered  for  every  value!  
eltehaem  at  N  dot  O  dot  S  dot  P  dot  A  dot  M  dot  free  dot  poltronic  dot  net
11-Aug-2001  10:26  
>array_unique()  will  keep  the  first  key  encountered  
>for  every  value,  and  ignore  all  following  keys.  

This  is  true  only  in  PHP  4.0.4pl1,  i.e.  the  code  below:  

<?php  
$temp  =  Array  ('pl',  'pl',  'en',  'en',  'cz',  'de',  'en',  'pl');  
print_r($temp);  
print_r(array_unique($temp));  
?>  

Will  produce  this  output:  

Array  
(  
      [0]  =>  pl  
      [1]  =>  pl  
      [2]  =>  en  
      [3]  =>  en  
      [4]  =>  cz  
      [5]  =>  de  
      [6]  =>  en  
      [7]  =>  pl  
)  
Array  
(  
      [0]  =>  pl  
      [2]  =>  en  
      [4]  =>  cz  
      [5]  =>  de  
)  

And  in  PHP  4.0.3pl1  will  produce  this  output:  

Array  
(  
      [0]  =>  pl  
      [1]  =>  pl  
      [2]  =>  en  
      [3]  =>  en  
      [4]  =>  cz  
      [5]  =>  de  
      [6]  =>  en  
      [7]  =>  pl  
)  
Array  
(  
      [4]  =>  cz  
      [5]  =>  de  
      [6]  =>  en  
      [7]  =>  pl  
)  

This  little  function  resolves  the  problem:  

<?php  
function  my_array_unique(&$old){  
      $new  =  array();  
      foreach($old  as  $key  =>  $value){  
              if(!in_array($value,  $new))  $new[$key]  =  $value;  
      }  
      return  $new;  
}  
?>  
az  at  top-webdesign  dot  de
10-Jul-2001  04:00  
Attention!  
If  you  use  array_unique  be  aware  of  data-types!  (I  spent  hours  of  debugging  because  of  that  ...).  

For  example,  if  you've  got  an  array  containing  a  '3'  as  number  and  another  '3'  as  string  it  won't  be  eliminated  by  array_unique.  

An  Example  where  this  can  happen,  without  really  thinking  about  it:  

I've  got  an  article-list  with  product-numbers  where  the  third  and  fourth  digit  is  the  code  for  the  producer.  So  I  read  in  the  file  an  process  it  line  by  line  and  put  each  producer-code  into  an  array:  
------------------------------  
<?php  
$i=0;  
while($line  =  fgets($csv,  10000)  {  
//  splitting  the  line,  product_no  is  the  first  part:  

$data  =  explode(";",  $line);  

//  putting  the  producer_code  into  an  array:  

$producer_id[$i]  =  trim(substr($data[0],  2,  2));  

//  make  a  special  exception:  

if(trim(substr($data[0],  2,  2))  ==  40)  {  
$producer_id[$j]  =  '30';  
}  

//  in  the  above  line  if  you  leave  the  30  without  the  ''  
//  array_unique  won't  work!  

$i++;  
}  

$producer_ids  =  array_values(array_unique($producer_id));  
?>  
-------------------------------  
Result  is  to  have  all  producer-ID's  in  an  array  without  dupes.  
az  at  top-webdesign  dot  de
10-Jul-2001  03:38  
@lefeuvrenicolas  

Use  the  above  mentioned  combination  with  "array_values"  -  then  it  works.  

So  do  it  like  this:  
--------------------  
<?php  
$truc  =  array("l810u00","l810u00","l810q00");  
$machin  =  array_values(array_unique($truc));  
for($i=0;$i  <  count($machin)  ;  $i++){  
echo  $machin[$i]."\n";  
}  
?>  
--------------------  

But  it  is  strange  anyway  ...  
mads  dot  rebsdorf  at  am-vision  dot  dk
07-May-2001  08:55  
To  unique  an  array  in  newer  versions  of  php  -  i've  found  this  snippet  useful:  

<?php  
//  $old[0]  =  1  
//  $old[1]  =  1  
//  $old[2]  =  2  
//  $old[3]  =  1  
//  $old[4]  =  2  

$new  =  array();  

for($i=0;$i<count($old);++$i){  

      if(in_array($old[$i],  $new)  !=  "true"){  
              $new[]  =  $old[$i];  
      }  
}  

//$new  now  contains:  
//  
//$new[0]  =  1  
//$new[1]  =  2  
?>  

/mads  
rein  at  velt  dot  net
21-Apr-2001  03:44  
Following  code  copies  unique  values  from  MyArray  to  TempArray.  
Then  copies  non-empty  elements  from  TempArray  to  UniqueArray.  

Not  the  most  elegant  solution,  but  it  works.  

<?php  
$TempArray  =  array_unique($MyArray);  
while  (list($index,$data)=each($TempArray))  {  
          if  (isempty($data))  {  
                  $UniqueArray[$index]=$data;  
          }  
}  
?>  
sneze  at  yahoo  dot  com
10-Feb-2001  12:47  
$users  =  array_unique($online_users);  

foreach($users  as  $value){  
echo  $value;  
}  

saved  my  day  
burno  at  33-24-36  dot  com
10-Nov-2000  06:28  
Or  just  do  a  usort($myArray,"return  -1");  after  the  usage  of  array_unique  
matthew_dean  at  hotmail  dot  com
26-Oct-2000  10:04  
Re:  Useful  comments  from  jllamas@bal.com.mx  

If  you  are  using  a  numerically  indexed  array  and  you  want  to  make  it  unique  but  *with*  consecutive  indices,  you  can  use  array_values(array_unique($myArray));  
jllamas  at  bal  dot  com  dot  mx
26-Sep-2000  12:25  
It  seems  that  array_unique  creates  an  exact  copy  of  the  original  array  and  then  elimitates  duplicate  values.  It  does  NOT  change  the  "internal  references"  of  the  array.  For  example:  

<?php  
      $test_alfa  =  array();  
      $test_alfa[0]  =  "aa";  
      $test_alfa[1]  =  "aa";  
      $test_alfa[2]  =  "aa";  
      $test_alfa[3]  =  "bb";  
      $test_alfa[4]  =  "aa";  
      $test_alfa[5]  =  "bb";  
      $test_alfa[6]  =  "cc";  
      $test_alfa[7]  =  "bb";  
      
      $test_beta=  array_unique($test_alfa);  
      $numValues  =  count($test_beta);  
      for  ($i  =  0  ;  $i  <=  7  ;  $i++)  
              echo("test_beta[$i]  =  $test_beta[$i]  <br>");  
      echo  ("Number  of  elements  in  test_beta  =  $numValues  ");  
?>  
will  give  you  the  following  output:  

test_beta[0]  =  
test_beta[1]  =  aa  
test_beta[2]  =  
test_beta[3]  =  
test_beta[4]  =  
test_beta[5]  =  bb  
test_beta[6]  =  cc  
test_beta[7]  =  
Number  of  elements  in  test_beta  =  3  

The  point  is  that  you  won't  get  the  output  you'd  expect  if  you  think  that  the  values  of  the  non  duplicate  elements  are  located  in  the  first  three  array  locations.  

      $numValues  =  count($test_beta);  
      for  ($i=0;$i<=$numValues;  $i++)  
              echo("test_beta[$i]  =  $test_beta[$i]  <br>");  
      echo  ("Number  of  elements  in  test_beta  =  $numValues  ");  

will  give  you:  

test_beta[0]  =  
test_beta[1]  =  aa  
test_beta[2]  =  
Number  of  elements  in  test_beta  =  3  

Hope  that  saves  u  some  debugging  time!  
sterba  at  locksley-west  dot  com
05-Sep-2000  03:30  
Maybe  this  will  come  handy  for  PHP3  users:  
<?php  
for  ($a  =  0;  $a  <  $arraylength;  $a++){  
      if  (($a  >  0)&&($array[$a]  <>  $array[$a-1]))  
              $uniquearray[$a]  =  $array[$a];  

      $a++;  
}  
?>  

You  can  even  skip  the  $a>0  test,  I  believe...  not  bulletproof,  but  much  shorter.  
moose  at  ucdavis  dot  edu
15-Aug-2000  05:08  
Here's  a  little  function  I  wrote  that's  similar  to  array_unique,  for  PHP3  users.    It  actually  removes  duplicated  elements,  but  only  works  for  1  dimensional  arrays.    It  also  doesn't  return  a  value,  it  changes  the  input  array:  

<?php  
function  array_unique(&$thearray)  
{sort($thearray);  
  reset($thearray);  

  $newarray  =  array();  
  $i  =  0;  

  $element  =  current($thearray);  
  for  ($n=0;$n<sizeof($thearray);$n++)  
  {if  (next($thearray)  !=  $element)  
    {$newarray[$i]  =  $element;  
      $element  =  current($thearray);  
      $i++;  
    }  
  }  
  $thearray  =  $newarray;  
}  
?>

1713 view

4.0 stars