How to use PHP array_diff_assoc() and array_unique() Functions In PHP

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
)

PHP Program to Find Duplicate Elements from an Array

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:

Table of Content

  • Using PHP array_diff_assoc() and array_unique() Functions
  • Using PHP for() Loop
  • Using array_count_values() and array_filter()
  • Using array_filter and array_keys

Similar Reads

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....

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....

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....

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....