1

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?

0

3 Answers 3

2
$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;
}
Sign up to request clarification or add additional context in comments.

Comments

2
  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

Comments

1

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

1 Comment

He doesn't want unique values from an array, he wants to match those values which appear 3 times. Array unique would "match" those that appear 2 times as well, so it's no good.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.