PPS
PPS

Reputation: 552

Check for unique and non-unique values in array

We would like to get the result with full information, like Unique = Value1, Value2. Duplicate= Value1 . We have an array which is mention below it a sample array.

$array1 = array('John Wilkins', 'Poul Warner', 'Rodger Smith', 'David Bentham', 'David Wilkins', 'Brian Smith', 'David Warner', 'John Wilkins', 'Poul Warner', 'David Wilkins', 'Brian Smith', 'David Warner', 'John Wilkins', 'Poul Warner', 'David Bentham', 'David Wilkins');

We'll use this function with Numeric values. We would like to print the result in this format.

John Wilkins | Duplicate
Poul Warner  | Duplicate
Rodger Smith  | Unique

and so on.

Upvotes: 5

Views: 8825

Answers (2)

jensgram
jensgram

Reputation: 31508

This is pretty much what array_count_values() does:

<?php

$array1 = array('John Wilkins', 'Poul Warner', 'Rodger Smith', 'David Bentham', 'David Wilkins', 'Brian Smith', 'David Warner','John Wilkins', 'Poul Warner', 'David Wilkins', 'Brian Smith', 'David Warner','John Wilkins', 'Poul Warner', 'David Bentham', 'David Wilkins');

$counts = array_count_values($array1);
foreach ($counts as $name => $count) {
    print $name . ' | ' . ($count > 1 ? 'Duplicate' : 'Unique') . "\n";
}

Output:

John Wilkins | Duplicate
Poul Warner | Duplicate
Rodger Smith | Unique
David Bentham | Duplicate
David Wilkins | Duplicate
Brian Smith | Duplicate
David Warner | Duplicate

(demo)

Upvotes: 16

K6t
K6t

Reputation: 1845

$array = array('apple', 'orange', 'pear', 'banana', 'apple',
'pear', 'kiwi', 'kiwi', 'kiwi');

print_r(array_count_values($array));
will output

Array
(
   [apple] => 2
   [orange] => 1
   [pear] => 2
   etc...
)

Upvotes: 3

Related Questions