tags:

views:

55

answers:

2

Hi,

I have 5 textfields for user input in a form namely:

username1, username2, username3, username4 and username5

I would like to know how should I write my php code such that I will be able to check if there is any duplicates between the 5 textfields during POST?

I can only think of comparing (username1 !== username2) and so on, but I think there should be simpler way to do it right? How should I be able to do it?

Thank you very much.

+7  A: 

The array_unique() function takes an array, removes the duplicates, and gives it back to you. So you can use it to test for duplicates by checking the length of the returned array, like this.

$usernames = array($username1, $username2, $username3, $username4, $username5);

$no_dupes = array_unique($usernames);
if (count($no_dupes) == count($usernames)) {
    // we have no duplicates
}
yjerem
Elegant and flexible solution!
wallyk
Thanks jeremy! that's what I am looking for.
jl
+1  A: 

array_count_values will tell you which name was repeated.

$names = array($username1, $username2, $username3, $username4, $username5);

foreach(array_count_values($names) as $name => $times) {
    if($times > 1) {
        echo "Error: Username '$name' is used $times times!\n";
    }
}

You should also consider filtering the values through trim() and strtolower().

too much php