PHP Program to Find Duplicate Elements from an Array
Last Updated :
03 Jul, 2024
Given an array containing some repeated elements, the task is to find the duplicate elements from the given array. If array elements are not repeated, then it returns an empty array.
Examples:
Input: arr = [1, 2, 3, 6, 3, 6, 1]
Output: [1, 3, 6]
Input: arr = [3, 5, 2, 5, 3, 9]
Output: [3, 5]
There are two methods to get the duplicate elements from an array, these are:
Using PHP array_diff_assoc() and array_unique() Functions
The PHP array_diff_assoc() function is used to find the difference between one or more arrays. This function compares both the keys and values between one or more arrays and returns the difference between them.
The PHP array_unique() function is used to remove the duplicate elements from an array.
Syntax:
array_diff_assoc($array, array_unique($array))
Example: This example uses array_diff_assoc() and array_unique() functions to get the unique elements in an array.
PHP
<?php
$arr = array(3, 5, 2, 5, 3, 9);
$findDuplicate = array_diff_assoc(
$arr,
array_unique($arr)
);
print_r($findDuplicate);
?>
OutputArray
(
[3] => 5
[4] => 3
)
First, we will declare and initialize an array, and use PHP sizeof() function to get the array size. Then we will use nested for() loop to compare the array elements, and if two elements are same, then print the value. If no value is repeated, then it will not print any value.
Syntax:
for ($i = 0; $i < $arr_length; $i++) {
for ($j = $i + 1; $j < $arr_length; $j++) {
// checking for duplicates
if ($array[$i] == $array[$j])
echo "$array[$j] ";
}
}
Example: This example uses nested for loop to get the unique elements from an array.
PHP
<?php
// Declare an array with repeated elements
$arr = array(2, 3, 5, 3, 5, 9);
// Get the length of an array
$length = sizeof($arr);
// Using Nested for Loop to get the
// repeated elements
for ($i = 0; $i < $length; $i++) {
for ($j = $i + 1; $j < $length; $j++) {
if ($arr[$i] == $arr[$j])
echo "$arr[$j] ";
}
}
?>
Using array_count_values() and array_filter()
To find duplicate elements from an array in PHP using array_count_values() and array_filter(), first count the occurrences of each value. Then, filter the counts to include only those greater than one, and extract the corresponding keys as duplicates.
Example
PHP
<?php
$arr = array(3, 5, 2, 5, 3, 9);
// Use array_unique() to get an array with only unique elements
// Use array_diff_assoc() to find elements that are not present in the unique array
$findDuplicate = array_diff_assoc(
$arr,
array_unique($arr)
);
print_r($findDuplicate);
?>
Output:
Array
(
[3] => 5
[4] => 3
)
Using array_filter and array_keys
Using array_filter and array_keys to find duplicates involves filtering the array to keep only elements that appear more than once, then utilizing `array_keys` to count occurrences. The filtered elements are then deduplicated with `array_unique` to get the final list of duplicates.
Example:
PHP
<?php
function findDuplicates($array) {
$duplicates = array_filter($array, function($item) use ($array) {
return count(array_keys($array, $item)) > 1;
});
return array_values(array_unique($duplicates));
}
$array = [1, 2, 3, 2, 4, 5, 3, 6, 7, 3];
$duplicates = findDuplicates($array);
print_r($duplicates);
?>
OutputArray
(
[0] => 2
[1] => 3
)
Using a Hash Map
This method involves creating an associative array to count occurrences of each element and then filtering out the elements that appear more than once.
Example: In this example, the findDuplicates function first initializes an associative array $elementCount to keep track of the count of each element. It then iterates through the input array, updating the count of each element. Finally, it iterates through the associative array to collect elements that have a count greater than one and returns these elements as duplicates.
PHP
<?php
function findDuplicates($array) {
$elementCount = [];
$duplicates = [];
// Count occurrences of each element
foreach ($array as $element) {
if (isset($elementCount[$element])) {
$elementCount[$element]++;
} else {
$elementCount[$element] = 1;
}
}
// Extract elements with count greater than one
foreach ($elementCount as $element => $count) {
if ($count > 1) {
$duplicates[] = $element;
}
}
return $duplicates;
}
// Example usage
$arr1 = [1, 2, 3, 6, 3, 6, 1];
$duplicates1 = findDuplicates($arr1);
print_r($duplicates1);
// Output: Array ( [0] => 1 [1] => 3 [2] => 6 )
$arr2 = [3, 5, 2, 5, 3, 9];
$duplicates2 = findDuplicates($arr2);
print_r($duplicates2);
// Output: Array ( [0] => 3 [1] => 5 )
?>
OutputArray
(
[0] => 1
[1] => 3
[2] => 6
)
Array
(
[0] => 3
[1] => 5
)
Using array_intersect and array_keys
This method involves iterating through the array, storing repeated elements in a new array, and then finding the common elements between the original array and the repeated elements array.
Example: In this example, the findDuplicates function first counts the occurrences of each element in the array. It then iterates through the associative array to store elements that have more than one occurrence in the $duplicates array. Finally, it uses array_intersect to find the common elements between the original array and the duplicates array, and array_unique to ensure the duplicate elements are unique in the result.
PHP
<?php
function findDuplicates($array) {
$elementCount = [];
$duplicates = [];
// Count occurrences of each element
foreach ($array as $element) {
if (isset($elementCount[$element])) {
$elementCount[$element]++;
} else {
$elementCount[$element] = 1;
}
}
// Store elements that have more than one occurrence
foreach ($elementCount as $element => $count) {
if ($count > 1) {
$duplicates[] = $element;
}
}
// Find common elements between original array and duplicates array
$duplicates = array_intersect($array, $duplicates);
// Get unique duplicate elements
$duplicates = array_unique($duplicates);
return $duplicates;
}
// Example usage
$arr1 = [1, 2, 3, 6, 3, 6, 1];
$duplicates1 = findDuplicates($arr1);
print_r($duplicates1);
// Output: Array ( [0] => 1 [2] => 3 [3] => 6 )
$arr2 = [3, 5, 2, 5, 3, 9];
$duplicates2 = findDuplicates($arr2);
print_r($duplicates2);
// Output: Array ( [0] => 3 [1] => 5 )
?>
OutputArray
(
[0] => 1
[2] => 3
[3] => 6
)
Array
(
[0] => 3
[1] => 5
)
Using array_flip() and array_diff_key()
This method involves using array_flip() to flip the keys and values of the array and then using array_diff_key() to find the elements that have been duplicated by comparing the flipped array with the original array.
Example:
PHP
<?php
function findDuplicates($array) {
$flippedArray = array_flip($array);
$diffArray = array_diff_key($array, $flippedArray);
$duplicates = [];
foreach ($diffArray as $value) {
if (!in_array($value, $duplicates)) {
$duplicates[] = $value;
}
}
return $duplicates;
}
// Example usage:
$arr = [1, 2, 3, 6, 3, 6, 1];
print_r(findDuplicates($arr));
$arr = [3, 5, 2, 5, 3, 9];
print_r(findDuplicates($arr));
?>
OutputArray
(
[0] => 1
[1] => 3
[2] => 6
)
Array
(
[0] => 3
[1] => 5
)
Similar Reads
PHP | Remove duplicate elements from Array You are given an Array of n-elements.You have to remove the duplicate values without using any loop in PHP and print the array. Examples: Input : array[] = {2, 3, 1, 6, 1, 6, 2, 3} Output : array ( [6] => 2 [7] => 3 [4] => 1 [5] => 6 ) Input : array[] = {4, 2, 7, 3, 2, 7, 3} Output : arr
3 min read
Find the Most Frequent Element in an Array in PHP Given an array, i.e. $arr, the task is to find the most frequent element in an array. There are multiple ways to solve this problem in PHP we will be going to discuss them. These problems can be used during data analysis, Web Analytics, or highly used in fraud detection. Example: Input: $array = [1,
2 min read
How to check an element is exists in array or not in PHP ? An array may contain elements belonging to different data types, integer, character, or logical type. The values can then be inspected in the array using various in-built methods : Approach 1 (Using in_array() method): The array() method can be used to declare an array. The in_array() method in PHP
2 min read
How to remove duplicate values from array using PHP? In this article, we will discuss removing duplicate elements from an array in PHP. We can get the unique elements by using array_unique() function. This function will remove the duplicate values from the array.Syntax:array array_unique($array, $sort_flags);Note: The keys of the array are preserved i
4 min read
PHP Second most frequent element in an array Given an array we have to find the second most frequent element present in it. Examples: Input : array(3, 3, 4, 5, 5, 5, 9, 8, 8, 8, 8, 8); Output : Second most frequent element is: 5 Input : array("geeks", "for", "geeks"); Output : Second most frequent element is: for Here are some common approache
4 min read
How to Check an Array is Sorted or Not in PHP? Given an array, the task is to check whether the given array is sorted or not. Arrays are often used to store and manipulate data. One common task is to check if an array is sorted in ascending or descending order. This article will explore different approaches to determine whether an array is sorte
3 min read
How to find the index of an element in an array using PHP ? In this article, we will discuss how to find the index of an element in an array in PHP. Array indexing starts from 0 to n-1. Here we have some common approachesTable of ContentUsing array_search() FunctionUsing array_flip()Using a custom functionUsing a foreach LoopUsing array_keys FunctionUsing ar
6 min read
How to get total number of elements used in array in PHP ? In this article, we will discuss how to get total number of elements in PHP from an array. We can get total number of elements in an array by using count() and sizeof() functions. Using count() Function: The count() function is used to get the total number of elements in an array. Syntax: count(arra
2 min read
PHP | Find Intersection of two arrays You are given two arrays of n-elements each. You have to find all the common elements of both elements, without using any loop in php and print the resulting array of common elements. Example: Input : array1[] = {3, 5, 2, 7, 9}, array2[] = {4, 3, 2, 7, 8} Output : array ( [0] => 3, [1] => 2, [
2 min read
Find sum of count of duplicate numbers in all subarrays of given array Given an array arr[] of size N. The task it to find the sum of count of duplicate numbers in all subarrays of given array arr[]. For example array {1, 2, 3, 2, 3, 2} has two duplicate elements (i.e, 2 and 3 come more than one time in the array). Examples:Input: N = 2, arr = {3,3}Output: 1Explanation
6 min read