erwinleonardy
erwinleonardy

Reputation: 486

Shortcut for checking if all $_POST fields are filled in 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!

Upvotes: 5

Views: 5046

Answers (4)

ssudaraka
ssudaraka

Reputation: 325

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

Upvotes: 5

Panda
Panda

Reputation: 6896

You can use a foreach() loop to check each $_POST value:

foreach ($_POST as $val) {
    if(empty($val)) echo 'You have not filled up all the inputs';
}

Upvotes: 2

Josh S.
Josh S.

Reputation: 597

Here's a function I just authored that might help.

if any of the arguments you pass is empty, it returns false. if not it'll return true.

function multi_empty() {
    foreach(func_get_args() as $value) {
        if (!isset($value) || empty($value)) return false;
    }
    return true;
}

Example

multi_empty("hello","world",1234); //Returns true 
multi_empty("hello","world",'',1234); //Returns false
multi_empty("hello","world",1234,$notset,"test","any amount of arguments"); //Returns false 

Upvotes: 2

roullie
roullie

Reputation: 2820

You can use array_filter and compare both counts

if(count(array_filter($_POST))!=count($_POST)){
    echo "Something is empty";
}

Upvotes: 11

Related Questions