Reputation: 117
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.
Upvotes: 2
Views: 490
Reputation: 98991
Late answer, but because I'm on a ternary mood, here it goes:
echo (in_array("someuser", array("user1","user2"))) ? "Got Username" : "Username not found";
Upvotes: 1
Reputation: 560
Try the solution of the other users but you could combine with Traits.
You could create a Trait called VerifyUser
with the next content:
trait VerifyUser {
public function verifyUser($user){
if (in_array($username, $usersArray)){
echo $username . "is already taken";
}else {
array_push($usersArray, $username);
}
}
}
Don't forget add your custom array to your class if you are working in a OOP environment. Add this trait with the
use VerifyUser
instruction.
class UsersCollection{
use VerifyUsers
$usersArray= ["user1", "user2"];
$this->verifyUser("user1"); //It echo the custom message you could return a boolean value and then specify a custom behaviour.
}
Upvotes: 0
Reputation: 397
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.)
Upvotes: 2
Reputation: 3574
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"
}
?>
Upvotes: 4