Last updated on July 2nd, 2019 at 11:05 am

This tip helps you to find duplicates values in an array and return the duplicated values in an array with index in an efficient way.

$array = ["5-product", "5-product", "8"];

$duplicateProduct = array_unique(array_diff_assoc($array, array_unique($array)));

echo "<pre>";
print_r($duplicateProduct);

// Another method to find duplicate data in array
$dups = array();
foreach(array_count_values($array) as $val => $c)
    if($c > 1) $dups[] = $val;
  
print_r($dups);
$unique = array_unique($array);

// Get index of Duplicates data from array
$duplicate_keys = array_keys(array_intersect($array, $duplicateProduct));
print_r($duplicate_keys);

Hope this tip help you.

Posted in: PHP