Zohaib
Zohaib

Reputation: 159

How do I find duplicates in a PHP array?

Is there anyway to find duplicates in array values? like:-

$cars = array("Volvo", "BMW", "Toyota", "BMW", "Toyota");

As BMW and Toyota occurs twice output would be BMW and Toyota i know about array_search() but in that you have to provide what you want to search.. i can match array value with respect to key but size of array can vary, It would be great if anyone help me out.

Upvotes: 5

Views: 5080

Answers (2)

Hiruna De Alwis
Hiruna De Alwis

Reputation: 64

You can do like this

function array_match_dump($array){
   return array_unique(array_diff_assoc($array,array_unique($array)));
}

Upvotes: 1

Eddie
Eddie

Reputation: 26844

One option is using array_count_values() and include only array elements with more than one values.

$cars = array("Volvo", "BMW", "Toyota", "BMW", "Toyota");

foreach( array_count_values($cars) as $key => $val ) {
    if ( $val > 1 ) $result[] = $key;   //Push the key to the array sice the value is more than 1
}

echo "<pre>";
print_r( $result );
echo "</pre>";

This will result to:

Array
(
    [0] => BMW
    [1] => Toyota
)

Doc: array_count_values()

Upvotes: 9

Related Questions