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
Remove First Element from an Array in PHP
Given an array, the task is to remove the first element from an array in PHP. Examples:Input: arr = [1, 2, 3, 4, 5, 6, 7]; Output: 2, 3, 4, 5, 6, 7 Input: arr = [3, 4, 5, 6, 7, 1, 2] Output: 4, 5, 6, 7, 1, 2Below are the methods to remove the first element from an array in PHP:Table of ContentUsing
3 min read
How to delete an Element From an Array in PHP ?
To delete an element from an array means to remove a specific value or item from the array, shifting subsequent elements to the left to fill the gap. This operation adjusts the array's length accordingly, eliminating the specified element.This article discusses some of the most common methods used i
4 min read
Sort an array of dates in PHP
We are given an array of multiple dates in (Y-m-d) format. We have to write a program in PHP to sort all the dates in the array in decreasing order. Examples : Input : array("2018-06-04", "2014-06-08", "2018-06-05") Output : 2018-06-05 2018-06-04 2014-06-08 Input : array("2016-09-12", "2009-09-08",
2 min read
How to get elements in reverse order of an array in PHP ?
An array is a collection of elements stored together. Every element in an array belong to a similar data type. The elements in the array are recognized by their index values. The elements can be subjected to a variety of operations, including reversal. There are various ways to reverse the elements
4 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
Find the Second Largest Element in an Array in PHP
We will be given with an integer array, i.e. $array1 or $ array2, and the task is to find the second largest element in the array. There are multiple ways to approach and solve this problem however using sorting is the most common and concise approach as we use the rsort() function for further opera
3 min read
Removing Array Element and Re-Indexing in PHP
In order to remove an element from an array, we can use unset() function which removes the element from an array, and then use array_values() function which indexes the array numerically automatically. Function Usedunset(): This function unsets a given variable. Syntax:void unset ( mixed $var [, mix
2 min read
PHP | Deleting an element from array using array_diff()
Given an array, we have to delete an element from that array using the array_diff() function in PHP.Examples:Input : $arr = array(2, 8, 9, 7, 6, 5); $arr = array_diff($arr, array(9)); Output : Array ( [0] => 2 [1] => 8 [3] => 7 [4] => 6 [5] => 5 ) Input : $arr = array("shubham", "aksh
2 min read
PHP | Separate odd and even elements from array without using loop
You are given an array of n elements in PHP. You have to separate the elements from the array based on the elements are odd or even. That is, print odd array and even array separately without traversing the original array or using any loop. Examples: Input : array(2, 5, 6, 3, 0) Output : Odd array:
3 min read