ksdst1
ksdst1

Reputation: 35

See if $_POST value matches an Array element value

I am very new to PHP. I am writing a "quiz" php form where the first goal is to require that users enter a valid "user account" name. I already have the lists of user accounts and created an array called $users. I think I need to put the verification php section above the form. I have declared the $users array and below it, start with:

if ($_SERVER["REQUEST_METHOD"] == "POST") {

               if (empty($_POST["uName"])) {
                    $uNameErr = "User name is required";
                    } 
                    else {
                         ....do something here
                          )
               }

I am not sure if I should use a foreach, for loop, or count through the array and compare the posted uName (username) with values of each element of the $users array. I can't produce the correct echo statements (as a test) with any of those methods. The last I have tried is:

if ($_SERVER["REQUEST_METHOD"] == "POST") {

               if (empty($_POST["uName"])) {
                    $uNameErr = "User name is required";
                    } 
                    else {

                        foreach($users as $value){

                            if ($value ===($_POST["uName"])){
                                    echo "needle is in the array";
                                } 
                                    else {
                                echo "needle is not in the array";      
                                }
                        }

Any help on this is highly welcomed!

Upvotes: 0

Views: 480

Answers (1)

Digits
Digits

Reputation: 2684

You can use in_array. This can easily replace your foreach loop. I find that I only use foreach when I need to operate on each value.

In this case you can do

if (in_array($_POST['uName'], $users))
echo 'they are in the array';
else echo 'they are not in the array';

additionally, you can replace

if ($_SERVER["REQUEST_METHOD"] == "POST") {

with

if (isset($_POST["uName"]){

Upvotes: 2

Related Questions