Nasir Iqbal
Nasir Iqbal

Reputation: 53

remove elements in php array that occur more than twice

I am looking for a function in php,where the function must delete values in the array that shows up three times or more? For example, if you give the function array(2, 4, 6, 3, 7, 7, 7, 4, 2, 0) the funciton will return array(2, 4, 6, 3, 4, 2, 0)

Upvotes: 0

Views: 993

Answers (3)

Muhammad Hassan Samee
Muhammad Hassan Samee

Reputation: 26

function FilterMyArray(array &$array){

$array_count=array_count_values($array);

foreach($array_count  as $key => $value){

 if($value > 2){
     foreach (array_keys($array, $key, true) as $unsetKey) {
     unset($array[$unsetKey]);
        }
      }
   }
}
$array=array(1, 3, 5, 2, 6, 6, 6, 3, 1, 9);
FilterMyArray($array);
print_r($array); 

Output

Array ( [0] => 1 [1] => 3 [2] => 5 [3] => 2 [7] => 3 [8] => 1 [9] => 9 )

`

Upvotes: 1

Sampath Liyanage
Sampath Liyanage

Reputation: 4896

You can use array_count_values() to get frequencies. Then use a foreach to get values that has frequency less than 3...

$array = array(2, 4, 6, 3, 7, 7, 7, 4, 2, 0);
$frq = array_count_values($array);
$result = array();
foreach ($frq as $key=>$value){
    if ($value < 3){
        $result[] = $key;
    }
}

Upvotes: 2

britter
britter

Reputation: 137

This will remove all duplicates, but you'd have to add to it to count the number of each of the values.

$a = array(2, 4, 6, 3, 7, 7, 7, 4, 2, 0);
$b = array();
for ($a as $key=>$value) {
  if (!in_array($value, $b)) {
    $b[] = $value;
  }
}
// array $b has all the values with no duplicates.

Upvotes: -1

Related Questions