简体   繁体   中英

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.

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 )

$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...
)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM