Sam Sam - 4 months ago 10
PHP Question

How can we find the Duplicate values in array using php?

I would like to know, how can we detect the duplicate entries in array...

Something like

$array = array("192.168.1.1", "192.168.2.1","192.168.3.1","192.168.4.1","192.168.2.1","192.168.2.1","192.168.10.1","192.168.2.1","192.168.11.1","192.168.1.4") ;


I want to get the number of Duplicity used in array (C class unique).
like this

192.168.1.1 = unique
192.168.2.1 = Duplicate
192.168.3.1 = unique
192.168.4.1 = unique
192.168.2.1 = Duplicate
192.168.2.1 = Duplicate
192.168.10.1 = unique
192.168.2.1 = Duplicate
192.168.11.1 = unique
192.168.1.4 = Duplicate (Modified)


I tried this code like this style

$array2 = array() ;

foreach($array as $list ){

$ips = $list;

$ip = explode(".",$ips);

$rawip = $ip[0].".".$ip[1].".".$ip[2] ;

array_push($array2,$rawip);

}


but i am unable to set the data in right manner and also unable to make the loop for matching the data.

modified values

Thanks

SAM

Answer

Try this : this will give you the count of each value

$array = array("192.168.1.1", "192.168.2.1","192.168.3.1","192.168.4.1","192.168.2.1","192.168.2.1","192.168.10.1","192.168.2.1","192.168.11.1") ;

$cnt_array = array_count_values($array)

echo "<pre>"; 
print_r($cnt_array);

$res = array();
foreach($cnt_array as $key=>$val){
   if($val == 1){
      $res[$key] = 'unique';
   }
   else{
      $res[$key] = 'duplicate';
   }
}

echo "<pre>";
print_r($res);
Comments