DMcg DMcg - 5 months ago 22
PHP Question

Remove duplicate values from assosciative array and return an associative array containing the duplicate values

I have associative array as so;

$arr = [1=>0, 2=>1, 3=>1, 4=>2]

I'd like to remove the duplicate values from the initial array and return those duplicates as a new array. So I would end up with something like;

$arr = [1=>0, 4=>2]

$new_arr = [2=>1, 3=>1]

Does PHP provide such a function or if not how would I achieve this?

Answer

Try:

Use array_filter() to get all duplicate values from array

Use array_diff() to get all unique values from array

$array = array(1=>0, 2=>1, 3=>1, 4=>2);
$counts = array_count_values($array);
$duplicates = array_filter($array, function ($value) use ($counts) {
    return $counts[$value] > 1;
});
print '<pre>';print_r($duplicates);

$result=array_diff($array,$duplicates);
print '<pre>';print_r($result);

Output:

Array
(
    [2] => 1
    [3] => 1
)

Array
(
    [1] => 0
    [4] => 2
)