4

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?

3 Answers 3

8
$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
)
Sign up to request clarification or add additional context in comments.

Comments

4

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

array_unique( array_diff_assoc( $array, array_unique( $array ) ) );

2 Comments

+1 for reading the question and fully comprehending what the OP was actually trying to accomplish :)
Thanks, rdlowrey, but I am the OP :) Feel free to rescind your upvote -- I found this answer shortly after I posed the question :P
-2

Use array_intersect;

<?php
$a = array(1,2,3,4);

$b = array(2,3);

var_dump(
    array_intersect($a,$b)
    );
//Outputs 2,3 as expected.
?>

1 Comment

OP has one array and he wants to find all entries that appear twice in that array. Intersect finds all entries that appear in the both of two arrays.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.