2

Possible Duplicate:
More concise way to check to see if an array contains only numbers (integers)
PHP checking if empty fields

I have form that submits 10 fields, and 7 of them should be filled, here is how i chek it now in PHP:

if (!$name || !$phone || !$email || !$mobile || !$email || !$state || !$street || !  $city) {
        echo '<div class="empty_p">You have empty fields!!!</div>';}
else{
        //process order or do something
}

My question is: is there more simple way to do this? Because sometimes I have even more strings to check (12-15)

3
  • 2
    If you add them into an array you could use a foreach. Commented Jun 8, 2012 at 14:14
  • 3
    @dynamic - if it's form data, chances are it's coming from an array in the first place ($_POST or $_GET) Commented Jun 8, 2012 at 14:16
  • @MarkBaker True, but he states he only needs to check 7 of the form-submitted variables. Commented Jun 8, 2012 at 14:18

7 Answers 7

5

Another possibility:

$elements = array($name, $email, $mobile);
$valid = true;

foreach ($elements as $element) {
    if (empty($element)) {
        $valid = false;
    }
}

if ($valid) {
    // complete
} else {
    // alert! some element is empty
}
Sign up to request clarification or add additional context in comments.

Comments

3

Something like this?

foreach($_POST as $key => $value) 
{
    if (empty($_POST[$key]))
    {
        echo '<div class="empty_p">'.$_POST[$key].' is empty.</div>';
    }
}

6 Comments

You can remove !isset($_POST[$key]) as it wouldn't be in the POST array that your looping if it was not already set.
Ghehe, you're right. Habits :P
Good stuff, tho it cant hurt to double check n case ;p
@Bono This line will throw an error also, because of a missing ) in if (empty($_POST[$key]) --- Should read as if (empty($_POST[$key]))
@Fred-ii- good eye ;) I've edited my answer
|
2

It's good to be specific about where this data should be expected, e.g. $_POST:

if (!isset($_POST['name'], $_POST['phone'], $_POST['email'], $_POST['mobile'], $_POST['state'], $_POST['street'], $_POST['city'])) {
    // something is up
}

You can shorten this code a little bit by creating an array with your required field names:

$required_fields = array('name', 'phone', 'email', 'mobile', 'state', 'street', 'city');

The 'check-for-existence' code can then be simplified to:

foreach ($required_fields as $f) {
    if (!isset($_POST[$f])) {
        // something is up
    }
}

The better way ™

However, you should seriously consider combining both existence and validation / sanitization checks. PHP provides a family of filter functions functions that you can use to validate and/or sanitize your input variables. For example, to get equivalent behavior as above:

$required_fields = filter_input_array(INPUT_POST, array(
    'name' => FILTER_UNSAFE_RAW,
    'email' => FILTER_VALIDATE_EMAIL,
));

if (is_null($required_fields) || in_array(null, $required_fields, true)) {
    // some fields are missing
}

Fields that exist but fail validation will be set to false, so this is how you detect such an event:

foreach ($required_fields as $name => $value) {
    if (false === $value) {
        // field $name failed validation (e.g. bad email format)
    } elseif (!strlen(trim($value))) {
        // field is empty
    }
}

Comments

1

The best way would be to create some sort of form validator. However you can use this function:

<?php
    function isAnyEmpty() {
        $total = 0;
        $args = func_get_args();
        foreach($args as $arg)
        {
            if(empty($arg)) {
                return true;
            }
        }

        return false;
    }
    $var1 = 1;
    $var2 = 'test';
    $var3 = '';

    if(isAnyEmpty($var1, $var2, $var3)) {
        echo 'empty fields!';
    }
?>

Comments

1

You could try creating a general validation class that could be reused and be more precise.

Some pseudo code:

<?

class validateFields {
    $validators = array(
        "name" => array(
            "empty" => array(
                "rule"          => "some regex",
                "errorMessage"  => "name may not be empty"
            ),
            "noNumbers" => array(
                "rule"          => "some regex",
                "errorMessage"  => "No numbers are allowed in the name field"
            )
        ),
        "otherVariable" => array(
            "atLeast50chars" => array(
                "rule"          => "some regex",
                "errorMessage"  => "This field must be at least 50 chars"
            )
        )
    );


    public function Validate($post){
        $errors = array();

        foreach($_POST as $key => $value){
            if(!array_key_exists($key, $validators)) {
                continue;
            }

            foreach($validators[$key] as $validator) {
                if(!preg_match($validator["rule"], $value) {
                    $errors[$key] = $validator["errorMessage"];
                    break;
                }
            }
        }

        return $errors;
    }
}


?>

Then in your code you could do something like:

$errors = Validate($_POST);
foreach($error as $errorMessage) {
    echo $errorMessage . "</br>";
}

Of course you could fancy this up, adding divs with classes right below/beside the concerning input field and load the $errorMessage into there. I'm sure there's loads of examples out there :)

Comments

1

You can write Foreach loop

  foreach($_POST as $key => $value) 
    {
        if (!isset($_POST[$key]) || empty($_POST[$key])
        {
            echo '<div class="something">You have empty fields!!!</div>';
        }
    }

3 Comments

empty == "" no need to do it twice, but also 0 would be considered empty.
Did you just copy my code? :/
This line will throw an error because of a missing ) in if (!isset($_POST[$key]) || empty($_POST[$key]) --- should read as if (!isset($_POST[$key]) || empty($_POST[$key]))
-1
<input type="text" name="required[first_name]" />
<input type="text" name="required[last_name]" />
...


$required = $_POST['required'];
foreach ($required as $req) {
   $req = trim($req);
   if (empty($req))
      echo 'gotcha!';
}

/* update */

OK! guys, easy...

You can make it more secure, just with type casting as all we programmers do for out coming data, like $id = (int) $_GET['id'], like $username = (string) addslashes($_POST['username']) and so on...;

$required = (array) $_POST['required'];

And then, what ever comes from post fields let them come, this code just seek what it need. That is it! Uhh...

6 Comments

beautiful. Never would have thought of that..well you learn something every day!
It's a bit late, that's why the imagination is running low here :P
Umm, this works great, but what if someone edit source code of form and change "required[first_name]" to nothing. Then nothing will be sent, and there will be missing data?
This is a horrible idea. A client modifying the HTML or simply sending a manually crafted POST request will be able to circumvent this check. While this will most likely not cause serious issues it's pretty ugly.
Security magically through addslashes and that already in the edit you did to focus on security. Ouch, that's horrorful. Also as ThiefMaster wrote, you don't whitelist the input variable names. That is so discusting. You get a -1 from me.
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.