Jump to content

array_unique


Beauford

Recommended Posts

I have been playing around with array_unique and a couple of other array functions, but can't get the combination of them I need t achieve my goal.

 

Take the following array  3 3 3 4 1.

 

I want to be able to count the duplicates and if the total of duplictes is 3 do something, if not 3 do nothing.

 

3 3 6 1 8 would be false

5 4 4 4 4 would be false

1 4 1 5 4 would do false

4 6 6 4 6 would be true

1 1 1 4 6 would be true

4 6 4 4 6 would be true

 

Thanks

Link to comment
https://forums.phpfreaks.com/topic/207713-array_unique/
Share on other sites

I would use the function array_count_values

<?php
$ary = array(3,3,3,4,1);
$check = false;
foreach (array_count_values($ary) as $v => $n) {
  if ($n == 3) {
       $check = true;
  }
}
if ($check) echo "There are 3 dups in the array";
?>

 

Ken

Link to comment
https://forums.phpfreaks.com/topic/207713-array_unique/#findComment-1085863
Share on other sites

I would use the function array_count_values

 

So would I but without the loop:

 

$array = array(3, 3, 3, 4, 1);

if(in_array(3, array_count_values($array))) {
echo "3 dups\n";
}

//or

if($num = array_search(3, array_count_values($array))) {
echo "3 dups of $num\n";
}

//or if there can be multiple duplicates

$array = array(3, 3, 3, 4, 4, 4, 1);

if($num = array_keys(array_count_values($array), 3)) {
echo "3 dups of " . implode(' and ',$num) . "\n";
}

 

3 dups

3 dups of 3

3 dups of 3 and 4

Link to comment
https://forums.phpfreaks.com/topic/207713-array_unique/#findComment-1085973
Share on other sites

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.