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 Program to Find lost element from a duplicated array
Given two arrays that are duplicates of each other except one element, that is one element from one of the array is missing, we need to find that missing element.Examples: Input: arr1[] = {1, 4, 5, 7, 9} arr2[] = {4, 5, 7, 9}Output: 11 is missing from second array.Input: arr1[] = {2, 3, 4, 5} arr2[]
4 min read
PHP Program to Delete Middle Element from an Array
Given an array, the task is to delete the middle element of the array. If the array has an even number of elements, the middle element can be considered as the one closer to the start of the array (the lower middle).These are the following approaches:Table of ContentUsing array_splice() functionUsin
3 min read
PHP Program to Sort an Array Elements in Descending Order
Given an array containing some elements, the task is to sort the array elements in descending order in PHP. Sorting elements of an array is a common operation in programming, and PHP provides several methods to accomplish this task.Table of ContentUsing rsort() FunctionUsing array_reverse() with sor
3 min read
PHP Program for Third largest element in an array of distinct elements
Given an array of n integers, find the third largest element. All the elements in the array are distinct integers. Example : Input: arr[] = {1, 14, 2, 16, 10, 20}Output: The third Largest element is 14Explanation: Largest element is 20, second largest element is 16 and third largest element is 14Inp
5 min read
Remove an Elements From End of an Array in PHP
Given an array "myArray", the task is to remove an element from its end. This operation is important in scenarios involving stacks, queues, and web development. In PHP, there are several approaches to achieve this One common method is using the array_pop() function, which removes the last element fr
3 min read
PHP Program to Find closest number in array
Given an array of sorted integers. We need to find the closest value to the given number. Array may contain duplicate values and negative numbers. Examples:Input : arr[] = {1, 2, 4, 5, 6, 6, 8, 9} Target number = 11 Output : 9 9 is closest to 11 in given array Input : arr[] = {2, 5, 6, 7, 8, 8, 9};
3 min read
Program to remove empty array elements in PHP
Given an array containing elements. The task is to remove empty elements from the array such as an empty string or a NULL element. Method 1: Using array_filter() Function. It is achieved by using array_filter() function. It also removes false values when declared using a callback function, however,
2 min read
How to Delete an Array Element based on Key in PHP?
Given an array containing elements. The task is to remove empty elements from the array based on the key in PHP.Example:Input: Array ( [0] => 'G' [1] => 'E' [2] => 'E' [3] => 'K' [4] => 'S' ) Key = 2Output: Array ( [0] => 'G' [1] => 'E' [3] => 'K' [4] => 'S' )Below are the
2 min read
PHP Program to Sort an Array in Ascending Order
Sorting array elements is a common operation in programming. PHP provides several methods to achieve this operation. In this article, we will explore various approaches to sort array elements of an array in ascending order.Table of ContentUsing sort() FunctionUsing asort() FunctionUsing array_multis
3 min read
PHP Program for Ceiling in a sorted array
Given a sorted array and a value x, the ceiling of x is the smallest element in array greater than or equal to x, and the floor is the greatest element smaller than or equal to x. Assume than the array is sorted in non-decreasing order. Write efficient functions to find floor and ceiling of x. Examp
4 min read