jl. jl. - 5 months ago 12
PHP Question

How to check duplicates for 5 textfields with PHP?

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.

Answer

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
}