Remove duplicate values from an array - php

2

I need to remove the 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 )

Everything that is duplicated is removed.

I tried with array_unique, but it eliminates the duplicate and shows how unique, being that I need to delete the two, would it have a shape?

    
asked by anonymous 22.11.2017 / 18:56

1 answer

3

If you just want to get the elements of the array that do not repeat, use the array_count_values() / a> it returns an array where the key is the values of the input array and the values are the amount found. Then it iterates the returned array and checks that the occurrence is equal to one.

In this example array_count_values() returns:

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

Output:

Array
(
    [0] => 2012
    [1] => 2013
    [2] => 2016
)
    
22.11.2017 / 19:13