Edy Elwood
Edy Elwood

Reputation: 137

Php check duplicate values in an array

I have a question about arrays.

I have made an array of id's.

The array looks a little like this.

$iIds[0] = 12  
$iIds[1] = 24  
$iIds[2] = 25  
$iIds[3] = 25  
$iIds[4] = 25  
$iIds[5] = 30

Now i need code to see if any of the values are in the array multiple times. Then, if the value is in the array 3 times, inject the value into another array.

I tried using array_count_values() , but it returns with the values as keys.

Can anyone help me with this?

Upvotes: 1

Views: 3716

Answers (3)

Er. Anurag Jain
Er. Anurag Jain

Reputation: 1793

For create array unique use array_unique php function and then for rearrange keys of array use array_values php function as given below.

$iIds[0] = 12 ;
$iIds[1] = 24 ; 
$iIds[2] = 25 ;
$iIds[3] = 25 ; 
$iIds[4] = 25 ;
$iIds[5] = 30 ;


$unique_arr = array_unique($iIds);
$unique_array  = array_values($unique_arr);

print_r($unique_array);

For getting an array of values are come 3 time in array as duplicate value

$iIds[0] = 12 ; 
$iIds[1] = 24 ;
$iIds[2] = 25 ;
$iIds[3] = 25 ;
$iIds[4] = 25 ;
$iIds[5] = 30 ;

$arr =  array_count_values($iIds);

$now_arr = array();
foreach($arr AS $val=>$count){
   if($count == 3){
      $now_arr[] = $val; 
   }
 }
 print_r($now_arr);

thanks

Upvotes: 1

Lee
Lee

Reputation: 10613

  1. Count values
  2. Filter array
  3. flip the array back to how you want it

    $cnt = array_count_values($iIds);

    $filtered = array_filter( $cnt, create_function('$x', 'return $x == 3;'));

    $final = array_flip($filtered);

or

array_flip(array_filter( array_count_values($iIds), create_function('$x', 'return $x == 3;')));

See: http://codepad.org/WLaCs5Pe

Edit

If there are chance of multiple values in the final array, i would recommend instead of flipping the filtered array, just use array_keys, so it would become:

$cnt = array_count_values($iIds);

$filtered = array_filter( $cnt, create_function('$x', 'return $x == 3;'));

$final = array_keys($filtered);

See: http://codepad.org/ythVcvZM

Upvotes: 2

Salketer
Salketer

Reputation: 15711

$iIds[0] = 12  
$iIds[1] = 24  
$iIds[2] = 25  
$iIds[3] = 25  
$iIds[4] = 25  
$iIds[5] = 30
$counts = array_count_values($iIds);
$present_3_times = array();
foreach($counts as $v=>$count){
    if($count==3)//Present 3 times
        $present_3_times[] = $v;
}

Upvotes: 2

Related Questions