Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get an array of duplicate array values

Tags:

arrays

php

I have an array where I'm testing for duplicate values. I want to get an array of only the duplicate values, to give an error message to the user, noting which are the offending values. I tried

$duplicates = array_diff( $array_with_dupes, array_unique($array_with_dupes) );

But that didn't return the only the duplicate values -- instead I got an empty array.

What's a simple way to do this?

like image 926
user151841 Avatar asked Dec 27 '22 07:12

user151841


2 Answers

$arr = array('a','a','b','c','d','d','e');
$arr_unique = array_unique($arr);
$arr_duplicates = array_diff_assoc($arr, $arr_unique);
print_r($arr_duplicates);

The above will return

Array
(
    [1] => a
    [5] => d
)
like image 80
kba Avatar answered Jan 11 '23 08:01

kba


An answer is here ( Use array_diff_assoc instead of array_diff):

array_unique( array_diff_assoc( $array, array_unique( $array ) ) );
like image 33
user151841 Avatar answered Jan 11 '23 08:01

user151841