Denoteone
Denoteone

Reputation: 4055

Check all $_POST Variable at once

instead of checking all my post variables from a form one at a time is there any way to run one check to atleast verify that they are not empty something like

if(!isset(ALL $_POST)){
echo "one of your fields is not completed.";
}

Upvotes: 2

Views: 4984

Answers (3)

Damiqib
Damiqib

Reputation: 1077

Can't be done like the way you're thinking (as PHP has no way of knowing what values there should be).

But you could it like this:

<?php
  $POSTvaluesToCheck = array('write', 'here', 'all', 'the', 'values', 'that', 'are', 'mandatory', 'to', 'exist');

  foreach($POSTvaluesToCheck as $key) {
    if(!isset($_POST[$key]) {
      echo $key . ' not set correctly!';
    }
  }
?>

Upvotes: 0

Nicole
Nicole

Reputation: 33207

No because how would your program know which should exist?

However, if you have a list of fields that are expected, you can easily write a function to check. I called it array_keys_exist because it does the exact same thing as array_key_exists except with multiple keys:

function array_keys_exist($keys, $array) {
    foreach ($keys as $key) {
        if (!array_key_exists($key, $array)) return false;
    }
    return true;
}

$expectedFields = array('name', 'email');

$success = array_keys_exist($expectedFields, $_POST);

Upvotes: 1

Brad Mace
Brad Mace

Reputation: 27886

You can create an array of required fields and loop through that

$required_fields = array("name", "address", "phone", "email");
foreach ($require_fields as $field) {
    if (!strlen($_POST[$field])) {
        echo "$field cannot be empty";
    }
}

Upvotes: 10

Related Questions