Open In App

PHP Program to Find Duplicate Elements from an Array

Last Updated : 29 Mar, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

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);
  
?>


Output

Array
(
    [3] => 5
    [4] => 3
)

Using PHP for() Loop

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] ";
    }
}
  
?>


Output

3 5 


Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads