Jon Jon - 6 months ago 23
PHP Question

Comparing user input with PHP array

For a small project I'm working on I want a user to be able to register an account using a username however I don't want to configure a database i.e I just want to compare the username the user inputs with a PHP array.

<?php
$a=array(“user1”,user2”);
for($a =0; $x<$arrlength; $a++){
if($username == $a){ //i want to say if $username is in array alert this and do nothing
$echo print a new username, already taken;
return false;
else(
array_push($a,username);?>


I'm working with the w3 schools PHP examples and I have something like this (the user inputs a 'username' in a form. I was wondering how you would actually implement this functionality properly.

Answer

You could simply use the in_array() function:

<?php
$usernames = array("user1", "user2", "user3", "user4");

if (in_array("username_from_user_input", $usernames)) {
    echo "Got Username";
}else{
    echo "Username not found"
}

?>
Comments