Remove duplicate values from an array - php

Asked

Viewed 1,317 times

4

I need to remove duplicate values from a PHP array, for example:

$array = ('2015', '2015', '2012', '2013', '2014', '2014', '2016')

I wish I had the output:

Array ( [0] => 2012 [1] => 2013 [2] => 2016 )

that all that is duplicated be removed.

I tried with array_unique, but it eliminates the duplicate and shows as unique, being that I need to eliminate the two.

Would have a way?

3 answers

5


If you just want to take the elements of the unrepeated array use the function array_count_values() it returns an array where the key is the input array values and the values are the amount found. Then iterate the returned array and check that the occurrence is equal to one.

In this example array_count_values() return:

Array
(
    [2015] => 2
    [2012] => 1
    [2013] => 1
    [2014] => 2
    [2016] => 1
)

Code:

$array = array('2015', '2015', '2012', '2013', '2014', '2014', '2016');
$valores = array_count_values($array);

$novo = array();
foreach ($valores as $k => $v){
    if($v === 1) $novo[] = $k;
}

echo "<pre>";
print_r($novo);

Exit:

Array
(
    [0] => 2012
    [1] => 2013
    [2] => 2016
)

3

A functional variation of accepted answer:

<?php

$arr = ['2015', '2015', '2012', '2013', '2014', '2014', '2016'];

$res = array_keys(array_filter(array_count_values($arr), function($v){
   return $v == 1;
}));

print_r($res);

/*Array
(
    [0] => 2012
    [1] => 2013
    [2] => 2016
)*/

Test the code on IDEONE

Where:

  1. Sane counted the occurrences of each value in the array.
    Array([2015] => 2,[2014] => 2, [2012] => 1, [2013] => 1, [2016] => 1)
  2. Sane filtered only those that do not repeat themselves.
    Array([2012] => 1, [2013] => 1,[2016] => 1)
  3. As array keys resulting is the solution of the problem.
    Array([0] => 2012, [1] => 2013, [2] => 2016)

2

First we create 2 functions to clean and remove duplicate values:

function limpaValoresDuplicados($num) {
    if($num<=1) return $num;
}

function removeValoresDuplicados($num) {
    if(!empty($num)) return $num;
}

We then call our array() and request the created functions:

$array = array('2015', '2015', '2012', '2013', '2014', '2014', '2016');

$valores = array_count_values($array);
$valores = array_map("limpaValoresDuplicados",$valores);
$valores = array_filter($valores, removeValoresDuplicados);

Return:

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

Array
(
    [2012] => 1
    [2013] => 1
    [2016] => 1
)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.