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