How to find duplicates in array in php

By Ved Prakash N | Jul 09, 2023 | PHP
Share : Whatsapp

https://www.fundaofwebit.com/post/how-to-find-duplicates-in-array-in-php

How to find duplicates in array in php


To find all the elements occurring more than once in the given array in PHP, you can use the following code:

$a = [2, 3, 1, 2, 3];
$duplicates = [];

foreach (array_count_values($a) as $value => $count) {
    if ($count > 1) {
        $duplicates[] = $value;
    }
}

echo "Elements occurring more than once: ";
print_r($duplicates);


Output:

Elements occurring more than once: Array
(
    [0] => 2
    [1] => 3
)


In this code, we use the array_count_values() function to get the count of each element in the array. We iterate over the resulting array using foreach loop. If the count of an element is greater than 1, we add it to the duplicates array. Finally, we print the elements occurring more than once using print_r().