How can I check for duplicates for 5 text fields using PHP?

I have 5 textfields

for user input on a form, namely:

username1, username2, username3, username4 and username5

I'd like to know

How should I write my php code so that I can check if there are duplicates between 5 text fields during POST?

I can only think of a comparison (username1 !== username2)

etc., but I think there must be an easier way to do this correctly?

How can i do this?

Many thanks.

+2


a source to share


2 answers


The function array_unique()

takes an array, removes duplicates, and returns it to you. So you can use it to check 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
}

      

+7


a source


array_count_values

will tell you which name has been 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()

.

+1


a source







All Articles