1

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.

1 Answer 1

2

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']
Sign up to request clarification or add additional context in comments.

Comments

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.