How can i get only duplicate values from an array in php?

You will need to make your function case insensitive to get the "Hello" => "hello" result you are looking for, try this method:

$arr = array[1=>'1233',2=>'12334',3 =>'Hello' ,4=>'hello', 5=>'U'];

// Convert every value to uppercase, and remove duplicate values
$withoutDuplicates = array_unique[array_map["strtoupper", $arr]];

// The difference in the original array, and the $withoutDuplicates array
// will be the duplicate values
$duplicates = array_diff[$arr, $withoutDuplicates];
print_r[$duplicates];

Output is:

Array
[
[3] => Hello
[4] => hello
]

Edit by @AlixAxel:

This answer is very misleading. It only works in this specific condition. This counter-example:

$arr = array[1=>'1233',2=>'12334',3 =>'Hello' ,4=>'HELLO', 5=>'U'];

Fails miserably. Also, this is not the way to keep duplicates:

array_diff[$arr, array_unique[$arr]];

Since one of the duplicated values will be in array_unique, and then chopped off by array_diff.

Edit by @RyanDay:

So look at @Srikanth's or @Bucabay's answer, which work for all cases [look for case insensitive in Bucabay's], not just the test data specified in the question.

10 Years Ago

Show only duplicate values from array without built in function

$arr = array[3,5,2,5,3,9];
I want to show only common elements i.e 3,5 as output.

Edited 10 Years Ago by rajendra87

Recommended Answers

How about something outside of the box:

$array = array[3, 5, 2, 5, 3, 9];
$duplicates = array_duplicates[$array];

function array_duplicates[array $array]
{
    return array_diff_assoc[$array, array_unique[$array]];
}

Jump to Post

Thanks for necroposting this dead thread back to the current list - not.

Jump to Post

All 7 Replies

10 Years Ago

The logic here is simple:

I am not a php developer so i am using c++ to explain this method !

int Array[6]= {3,5,2,5,3,9};

//create a for-loop for ArrayA

    for[int i=0; i

Chủ Đề