Nick Shears
Nick Shears

Reputation: 1133

PHP - If any array values match then remove all of them

I'm kind of stuck here on what I think must have quite a simple solution.

Say I have an array:

$A = array(1, 1, 2, 4, 6, 7, 7, 7, 13);

How could I possibly remove all of the values that occur more than once?

So I'm left with an array that looks like this

$A = array(2, 4, 6, 13);

I've tried using array unique, but that just removes duplicates leaving you with a single value. I need to use the following logic: if there are any values that match - then remove all of the values that match.

Upvotes: 1

Views: 176

Answers (4)

evalarezo
evalarezo

Reputation: 1153

Try this (with PHP >= 5.3):

$A = array_keys(array_filter(
    array_count_values($A), 
    function ($count) 
    {
        return $count == 1;
    }
));

Explanation:

array_count_values returns an array using the values of array as keys and their frequency in array as values.

array_filter Iterates over each value in the array passing them to the callback function (in this case anonymous function) . If the frequency is 1, the current value from array is returned into the result array.

array_keys returns the keys from the array, in this case the values with frequency equal to 1.

So, the compressed "one-line" form is:

$A=array_keys(array_filter(array_count_values($A),function($c){return $c==1;}));

Upvotes: 0

Richard Dev
Richard Dev

Reputation: 1170

You could always try something like this.

$A = array(1, 1, 2, 4, 6, 7, 7, 7, 13);

$A = array_count_values($A);
foreach($A as $key => $value) {
    if($value > 1)
      unset($A[$key]);
}
$A = array_keys($A);
print_r($A);

edit: fixed error

Array
(
    [0] => 2
    [1] => 4
    [2] => 6
    [3] => 13
)

Upvotes: 2

Amal Murali
Amal Murali

Reputation: 76656

You can use array_filter() with a custom callback to filter out the array values which repeat more than once:

function removeDuplicates($array) {
    $values = array_count_values($array);
    return array_filter($array, function($item) use ($values) {
        return $values[$item] === 1;
    });
}

Usage:

$A = array(1, 1, 2, 4, 6, 7, 7, 7, 13);
print_r( removeDuplicates($A) );

Output:

Array
(
    [2] => 2
    [3] => 4
    [4] => 6
    [8] => 13
)

Demo.

Upvotes: 2

James Smith
James Smith

Reputation: 1122

You can do this with abit of coding.

First see this SO post to get a list of all the duplicates using array_unique:

php return only duplicated entries from an array

Then you'll have to loop through the duplicates returned from the link above and do an array_search to return the index of the values and then array_splice to actually remove it.

I don't know of any code that will do this in one step for you.

Upvotes: 0

Related Questions