0

I have associative array like below

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

I would 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?

5
  • Do you want save indexes? Commented Jun 13, 2016 at 13:00
  • Yes, its important that I save indexes Commented Jun 13, 2016 at 13:04
  • Dharma's answer solved the problem that I asked. However, having moved on a little I find out that I now need the result like this '$arr = [1=>0, 2=>1, 3=>1, 4=>2, 5=>2, 6=>3]' Commented Jun 13, 2016 at 15:26
  • I think it's better to create a new qiestion with good explanation what numbers in array does mean Commented Jun 13, 2016 at 15:31
  • @dharma-parmar Dharma's answer solved the problem that I asked. However, having moved on a little I find out that I now need the result like this '$arr = [1=>0, 2=>1, 3=>1, 4=>2, 5=>2, 6=>3]' becomes '$arr = [1=>0, 4=>2, 6=>3]' '$new_arr = [[2=>1, 3=>1], [4=>2, 5=>2]] Commented Jun 13, 2016 at 15:31

2 Answers 2

2

You can get unique values from an array using array_unique and then compare the resulting array with array_diff_assoc

This will keep the indexes for both arrays, here's an example:

$arr = array(1=> 2, 2=>2, 3=>3);
print_r($arr);
$arr1 = array_unique($arr);
print_r($arr1);
$arr2 = array_diff_assoc($arr,$arr1);
print_r($arr2);

And the result:

Array
(
    [1] => 2
    [2] => 2
    [3] => 3
)
Array
(
    [1] => 2
    [3] => 3
)
Array
(
    [2] => 2
)
Sign up to request clarification or add additional context in comments.

Comments

0

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
)

1 Comment

Why should the OP "try this"? A good answer will always have an explanation of what was done and why it was done in such a manner, not only for the OP but for future visitors to SO.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.