1

Im trying to search for duplicate records inside an array... Easy enough ....

However I only want it to return values that are duplicates.. I dont want it to display the entire array values with the count ( there are over 400 million entries )

Here is the code I have tried ( it works in printing all values but not what I want )

    $query = mysqli_query($dbc, "SELECT * FROM `barcodes`");

while ($row = mysqli_fetch_row($query)) 
{ 
   $result_array[] = $row[16];

} 
print_r(array_count_values($result_array));

If anyone can help me it would really be appreciated as I've searched google and SO for over an hour and a half and not found what I want

Sample Of Array Print

[502185864797] => 1
[502185864798] => 1
[502185864799] => 1
[502185864800] => 1
[502185864801] => 2
[502185864802] => 2
[502185864803] => 2
[502185864804] => 2
[502185864805] => 2
[502185864806] => 2

I only want values that have a count > 1 displayed

Chris Yates
  • 243
  • 3
  • 16

3 Answers3

3

Depending on what you want displayed (for example this just gives the ID of a row) it would be better to try it in SQL...

SELECT ID 
    FROM `barcodes` 
    GROUP BY ID 
    HAVING count(ID)>1

The idea is to just retrieve ID's where the count value is more than one.

So this could look like...

$query = mysqli_query($dbc, "SELECT barcode 
    FROM `barcodes` 
    GROUP BY barcode 
    HAVING count(barcode)>1");

$result_array = mysqli_fetch_all($query, MYSQLI_ASSOC);

print_r($result_array);

If you wanted to have the number of times it exists, just add the count to the SELECT list...

SELECT ID, count(ID) times
    FROM `barcodes` 
    GROUP BY ID 
    HAVING count(ID)>1
Nigel Ren
  • 56,122
  • 11
  • 43
  • 55
1

Use array_count_values to get the count of each value.
Then use array_diff to filter out all unique values.
Array_keys get the value that array_count_values place in the keys.

$counts = array_count_values($arr);
$dupes = array_keys(array_diff($counts, [1]));

Edit after seeing the array:

$dupes = array_keys(array_diff($arr, [1]));

Is all you need. The array already shows the count of value (key).

Andreas
  • 23,610
  • 6
  • 30
  • 62
-1

i guess array_unique will do your work. Its a inbuilt function of php which removes all duplicates values from the array.

if you are intended to use only duplicates value then you can use another inbuilt function array_diff using both the arrays.

Pritam Jinal
  • 121
  • 9