Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

php return only duplicated entries from an array

Tags:

arrays

php

I want to retrieve all duplicated entries from a array. Is this possible in PHP?

array(     1 => '1233',     2 => '12334',     3 => 'Hello',     4 => 'hello',     5 => 'U' ); 

I want to return an array with just the duplicate value: “hello”.

Desired output array:

array(     1 => 'Hello',     2 => 'hello' ); 
like image 438
coderex Avatar asked Aug 11 '09 09:08

coderex


People also ask

How can I get only duplicate values from an array in PHP?

And a case-insensitive solution: $iArr = array_map('strtolower', $arr); $iArr = array_intersect($iArr, array_unique(array_diff_key($iArr, array_unique($iArr)))); array_intersect_key($arr, $iArr);

How can I get unique values from two arrays in PHP?

The array_diff() (manual) function can be used to find the difference between two arrays: $array1 = array(10, 20, 40, 80); $array2 = array(10, 20, 100, 200); $diff = array_diff($array1, $array2); // $diff = array(40, 80, 100, 200);


1 Answers

function get_duplicates ($array) {     return array_unique( array_diff_assoc( $array, array_unique( $array ) ) ); } 
like image 91
Alucard Avatar answered Oct 18 '22 00:10

Alucard