Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 525
PPS Avatar asked Dec 04 '22 21:12

PPS


2 Answers

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)

like image 68
jensgram Avatar answered Dec 10 '22 11:12

jensgram


$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...
)
like image 30
K6t Avatar answered Dec 10 '22 10:12

K6t