0

I have an array like this

$a=array(0=>1,1=>1,2=>5,3=>5,4=>10)

Now I want to find out the duplicate values and add those in to an array like this:

array_push($arrayOfones,$a['0'],$a['1'];
array_push($arrayOfFive,$a['2'],$a['5'];
2
  • $a['0'], $a['1'], $a['2'] and $a['5'] are not valid as shown in your code Commented Oct 23, 2012 at 7:12
  • array_count_values? Commented Oct 23, 2012 at 7:12

3 Answers 3

3

You could take a look at array_count_values

$ret = array_count_values($a);

// get the duplicate values
$ret = array_filter($ret, function ($var) {
  return $var > 1;
});

array_walk($ret, function(&$var, $key) {
  $var = array_fill(0, $var, $key);
});

var_dump($ret); // $ret[1] is $arrayOfOnes, $ret[5] is $arrayOfFive
Sign up to request clarification or add additional context in comments.

Comments

1

little simpler with no array functions other than count():

foreach($a as $key=>$value){
    $ip[$value][] = $key;
}

foreach($ip as $key=>$inner_arr){  
    if(count($inner_arr) > 1)
    $dup[$key] = $inner_arr ;
}

Comments

0
    $a=array(0=>1,1=>1,2=>5,3=>5,4=>10); 
    $c=0;
    foreach ($a as $key => $row) {

        if (!isset($rs[$row])) {
            $rs[$row][$key]= $key;
             $c = 1;
             $res[$row]['count'] = $c;
             $res[$row]['values'][$key] = $key;
        } 
        else {
            $res[$row]['count']++;
            $res[$row]['values'][$key] = $key;
        }
    }

Comments

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.