Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Shortcut for checking if all $_POST fields are filled in php

Tags:

php

I know that I can check if the superglobal $_POST is empty or not by using

empty / isset

However, I have many fields here. Is there any shortcut to check if all fields are filled? Instead of doing

if (!empty($_POST['a']) || !empty($_POST['b']) || !empty($_POST['c']) || !empty($_POST['d']).... ad nauseum)

Thanks in advance!

like image 773
erwinleonardy Avatar asked Feb 27 '16 02:02

erwinleonardy


People also ask

How do you check if there is a post in PHP?

Use isset() method in PHP to test the form is submitted successfully or not. In the code, use isset() function to check $_POST['submit'] method. Remember in place of submit define the name of submit button. After clicking on submit button this action will work as POST method.

How do I check if a field is empty in PHP?

PHP empty() Function The empty() function checks whether a variable is empty or not. This function returns false if the variable exists and is not empty, otherwise it returns true. The following values evaluates to empty: 0.

How to check if value exists in PHP?

The isset() function checks whether a variable is set, which means that it has to be declared and is not NULL. This function returns true if the variable exists and is not NULL, otherwise it returns false.


2 Answers

You can use array_filter and compare both counts

if(count(array_filter($_POST))!=count($_POST)){
    echo "Something is empty";
}
like image 119
roullie Avatar answered Oct 10 '22 17:10

roullie


You can loop through the $_POST variable.

For example:

$messages=array();
foreach($_POST as $key => $value){
    if(empty($value))
        $messages[] = "Hey you forgot to fill this field: $key";
} 
print_r($messages);
like image 43
ssudaraka Avatar answered Oct 10 '22 17:10

ssudaraka