H
H
Hannskod2018-02-27 01:07:08
PHP
Hannskod, 2018-02-27 01:07:08

How to get a list of duplicate elements of an array?

Hello, how can I get a list of duplicate elements in an array?

Answer the question

In order to leave comments, you need to log in

3 answer(s)
B
bkosun, 2018-02-27
@bkosun

$values = array('a', 'a', 'b', 'c', 'c');

$result = array_keys(array_filter(array_count_values($values), function($v){
   return $v > 1;
}));

print_r($values);
print_r($result);

Array
(
    [0] => a
    [1] => a
    [2] => b
    [3] => c
    [4] => c
)
Array
(
    [0] => a
    [1] => c
)

A
Alexander Pankratov, 2018-02-27
@xtrime

First example here: php.net/manual/ru/function.array-count-values.php
Example #1 Example using array_count_values()

<?php
$array = array(1, "hello", 1, "world", "hello");
print_r(array_count_values($array));
?>

The result of running this example:
Array
(
    [1] => 2
    [hello] => 2
    [world] => 1
)

Then we bypass the result of the function execution through foreach or array_filter and display only those keys that have a value greater than 1.
<?php
$array = array(1, "hello", 1, "world", "hello");
$array_count = array_count_values($array);
$duplicates = [];
foreach ($array_count as $k=>$v){
    if ($v > 1) $duplicates[] = $k;
}
print_r($duplicates);
?>

S
Sergey Gerasimov, 2018-02-27
@mrTeo

Perhaps it will help you:

function array_duplicates($arr)
{
    $arrUnique = array_unique(array_map("strtoupper", $arr));
    $duplicates = array_diff($arr, $arrUnique);
    return $duplicates;
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question