Compare Multiple Strings in Search of Duplicates

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
cfytable
Forum Commoner
Posts: 29
Joined: Thu May 12, 2005 3:36 pm

Compare Multiple Strings in Search of Duplicates

Post by cfytable »

I have six variable variables. It is OK if multiple variables have 'NULL' values, but, of those with values, I want to make sure that none have duplicate values. In other words, it is OK for both variable1 and variable2 to be equal to NULL, but I don't want variable1 and variable2 to have a value of "Tom". Any ideas on how best to compare the strings based on these requirements?
User avatar
John Cartwright
Site Admin
Posts: 11470
Joined: Tue Dec 23, 2003 2:10 am
Location: Toronto
Contact:

Post by John Cartwright »

put them into an array and array_unique() them
cfytable
Forum Commoner
Posts: 29
Joined: Thu May 12, 2005 3:36 pm

Post by cfytable »

Doesn't array_unique() just reduce the array to the non-duplicate items, as opposed to returning whether duplicates exist or not? Is there a function that does the latter?
User avatar
shiznatix
DevNet Master
Posts: 2745
Joined: Tue Dec 28, 2004 5:57 pm
Location: Tallinn, Estonia
Contact:

Post by shiznatix »

you could do

Code: Select all

foreach ($array as $val)
{
  if (false !== isset($new[$val]))
    $new[$val] = 'set';
  else
    //DUPLICATE AHHHHHH
}
you can change that to $new[$val] = $new[$val]++ to count how many times a option is duplicated too!
User avatar
feyd
Neighborhood Spidermoddy
Posts: 31559
Joined: Mon Mar 29, 2004 3:24 pm
Location: Bothell, Washington, USA

Post by feyd »

Code: Select all

if($array == array_unique($array)) { echo 'no duplicates there were, matey.'; } else { echo 'ya have duplicates matey.'; }
Post Reply