Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I find duplicates in a PHP array?

Tags:

arrays

php

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.

like image 813
Zohaib Avatar asked May 05 '18 17:05

Zohaib


1 Answers

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()

like image 177
Eddie Avatar answered Oct 18 '22 05:10

Eddie