Search code examples
phpif-statementargumentsstatements

What is the best way to supply many arguments to an if statement?


I have created a form with several user inputs but have the tedious task of checking whether each individual input is not empty before submission. Is there a quicker way, (such as using arrays perhaps) of listing all arguments to the if statement?

At the moment my code looks like this but if possible I would like it to be more efficient in future, like if I were to add more inputs.

<form action="sign-up.php" method="post" autocomplete="off" >
Name:<input type="text" name="name" />
Username:<<input type="text" name="username"  /><br />
Password:<input type="password" name="password1" /><br />
Re-type Password:<input type="password" name="password2"  /><br />
Email:<input type="text" name="email"  />
Address:<input type="text" name="address"  />
Post Code:<input type="text" name="postcode"  />
City:<input type="text" name="city"  />
<input class="submit" type="submit" value="sign up" />
</form>

<?php
if (!empty($_POST['name']) 
&& !empty($_POST['username']) 
&& !empty($_POST['password1']) 
&& !empty($_POST['password2']) 
&& !empty($_POST['email'])   
&& !empty($_POST['address'])
&& !empty($_POST['postcode']) 
&& !empty($_POST['city']) )
{
echo "information has been submitted";
}
else {
echo "please fill in all fields!"
}

?>

If you have any suggestions please comment.


Solution

  • So what this will do is loop through the $_POST values and check if they're empty. If one is found to be empty, it will set $hasErrorOccurred to true. The if statement below will determine if the input check is successful or not.

        $hasErrorOccurred = false;
    
        foreach ($_POST as $key => $value) {
            if (empty($_POST[$key])) {
                $hasErrorOccurred = true;
    
                break;
            }
        }
    
        if ($hasErrorOccurred) {
            // Your error code here.
        } else {
            // Your successful code here.
        }
    

    Reading material:

    break;