fikri ramadhan
fikri ramadhan

Reputation: 23

Keep Only Unique Values In Array

I have an obj like this:

$str([1,2,3,1,2,4,5])

I want to remove similar values from the array I want an output like:

$str([3,4,5])

Upvotes: 0

Views: 44

Answers (1)

chris85
chris85

Reputation: 23892

You could use array_count_values to count the unique terms in the array. Once you have that array just iterate over it and see if the term is present only once.

$str = array(1,2,3,1,2,4,5);
$array = array_count_values($str);
foreach($array as $value => $count) {
    if($count == 1) {
        $unique[] = $value;
    }
}

Demo: https://3v4l.org/4rTZE

Upvotes: 1

Related Questions