luqo33
luqo33

Reputation: 8361

Return unique values from an array in PHP without keep first copy of a duplicate

There are numerous threads on SF where users answer how to return unique values of a PHP array. The prevalent answer is:

$arrWtihDuplicates = ['a', 'a', 'a', 'b', 'c']

array_unique($arrWtihDuplicates) // will return ['a', 'b', 'c']

Is there a way to not have a returned at all?

Here is why this behavior can pose problems:

Let's come back to $arrWtihDuplicate. What if I want to return only duplicate values from this array? This would not work:

$arrWtihDuplicates = ['a', 'a', 'a', 'b', 'c'];
$withoutDuplicates = array_unique($arrWithDuplicates);

var_dump(array_diff($arrWtihDuplicates, $withoutDuplicates));

The above would return an empty array - both arrays share the same values so array_diff does not see a difference between them.

So to sum up, how can I return array values that do not have any duplicates so that:

['a', 'a', 'a', 'b', 'c'] becomes ['b', 'c']

or, conversely

['a', 'a', 'a', 'b', 'c'] becomes ['a', 'a', 'a'] - having done that array_diff(['a', 'a', 'a', 'b', 'c'], ['a', 'a', 'a']) would return only true uniques - b and c.

It seems overly complicated to make such computation in PHP.

Upvotes: 1

Views: 70

Answers (1)

Narendrasingh Sisodia
Narendrasingh Sisodia

Reputation: 21437

You can use set of PHP functions like as array_count_values, array_filter, & array_keys in order to get the result

$arr = ['a', 'a', 'a', 'b', 'c'];
$result = array_keys(array_filter(array_count_values($arr),function($v){ return $v==1;}));
print_r($result);//['b','c']

Upvotes: 2

Related Questions