sudeep cv
sudeep cv

Reputation: 1027

How to find duplicated values in PHP arrays?

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'];

Upvotes: 0

Views: 149

Answers (3)

Angelin Nadar
Angelin Nadar

Reputation: 9300

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 ;
}

Upvotes: 1

Ertunç
Ertunç

Reputation: 829

    $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;
        }
    }

Upvotes: 0

xdazz
xdazz

Reputation: 160843

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

Upvotes: 3

Related Questions