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.
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"
}
?>
If you want to save the registered accounts across requests, you have to store them in a file or database (or something else..), because the script is run from start on every requests.
Instead of looping over the array, you could also use the in_array function. ( http://php.net/manual/de/function.in-array.php )
To store the usernames, take a look at the file functions. (e.g. http://php.net/manual/en/function.file-put-contents.php to write to a file, and file_get_contents or file(..) to read a file). (For real projects, make sure to lock the file to prevent race conditions.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With