Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Comparing user input with PHP array

Tags:

php

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.

like image 628
Jon Avatar asked Nov 24 '25 10:11

Jon


2 Answers

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"
}

?>
like image 193
Geoherna Avatar answered Nov 25 '25 23:11

Geoherna


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.)

like image 25
M_T Avatar answered Nov 26 '25 01:11

M_T