Zain Sohail
Zain Sohail

Reputation: 464

Get common number of values in a single array

I want to get the common number of values from an array. Please check the following array

array(111) {
  [0]=> int(1807)
  [1]=> int(3013)
  [2]=> int(2989)
  [3]=> int(1815)
  [4]=> int(2993)
  [5]=> int(1807)
  [6]=> int(2999)
  [7]=> int(3003)
  [8]=> int(1815)
  [9]=> int(3009)
  [10]=> int(3013)
}

As you can see following are common items:

I need the output like:

array(1807, 3013, 1815)

Just to be clear array_unique wont work here, because it removes the duplicates from an array. I dont want to remove duplicates, I want to remove the non duplicate ones ..

Upvotes: 0

Views: 74

Answers (4)

Sifat Haque
Sifat Haque

Reputation: 6067

you can use simply array_unique and array_diff_assoc function . here is an example

$array = [1,2,3,1,2];
$unique_array = array_unique($array);
$array = array_diff_assoc($array, $unique_array);
$array = $array_unique($array);
print_r($array);

output :

Array ( [3] => 1 [4] => 2 ) 

Upvotes: 1

mega6382
mega6382

Reputation: 9396

Try the following:

$arr = array(
    1807,
    3013,
    2989,
    1815,
    2993,
    1807,
    2999,
    3003,
    1815,
    3009,
    3013,
);

$arr2 = $arr;

$recurring = [];

foreach($arr2 as $key => $value)
{
    unset($arr2[$key]);
    if(in_array($value, $arr2) && !in_array($value, $recurring))
    {
        $recurring[] = $value;
    }
}

var_dump($recurring);

this will give you all of the recurring values from your inside the $recurring variable. But be sure that you don't iterate the main array through the loop instead copy it like $arr2 = $arr;

Upvotes: 1

LostCause
LostCause

Reputation: 151

All you want are the duplicates.

Try this:

$duplicates= array();
foreach(array_count_values($arr) as $val => $c)
    if($c > 1) $duplicates[] = $val;
return $duplicates;

Upvotes: 0

Philipp
Philipp

Reputation: 15629

I'm not sure, if this could be easier done with php build in array functions, but a simple for loop with two temp array vars, will do the job to.

$array = [1,1,2,3,4,4];
$t = [];
$double = [];
foreach ($array as $item) {
    if (isset($t[$item])) {
        $double[$item] = true;
    }
    $t[$item] = true;
}
$values = array_keys($double);

Thought again about an other solution without the explicit loop and came up with this one, using array_reduce

$array = [1,1,2,3,4,4];
$values = [];
sort($array);
array_reduce($array, function($last, $current) use (&$values) {
    return $last == $current ? $values[$current] = $current : $current;
}, false);

print_r($values);

Upvotes: 0

Related Questions