0

I have a form in HTML and a code in PHP. The form contains a lot of different <input> things. And I want some text to output in a browser only if all the fields are not empty.

For example, for two fields called name and age, I would do the following:

if($_POST['name'] and $_POST['age']) { ... }

But here I have much more than two fields. What should I do?

nomicos
  • 65
  • 1
  • 6

3 Answers3

6

You could try something like this

$allSet = true;
foreach($_POST as $key => $value){
    if(empty($value)){
        $allSet = false;
        break;
    }
}
Dragony
  • 1,712
  • 11
  • 20
  • I like the method, but doesn't give the specific error message to what has been left blank. Also you should move this into a function + trim the value before verifying if it's empty – Daryl Gill Aug 26 '13 at 13:45
  • Sure, there is a lot that could be done. The goal is to point him in the right direction :) – Dragony Aug 26 '13 at 13:45
2

You can also try this if all inputs sent are required :

if (count(array_filter($_POST)) != count($_POST)) {
    // at least one input is empty
}

See array_filter()

This function returns the same array, without the values that are null, false, 0 or empty string. So if there is less entries in the filtered array than in the original, this means that at least one input has not been filled.

Edit : And it works !

Brewal
  • 8,067
  • 2
  • 24
  • 37
  • I like the solution, it's pretty slick, but it's probably not something that is on the right level for the guy that asked the question. – Dragony Aug 26 '13 at 13:54
  • @Dragony Yeah, I like to make it simple and short. Maybe that's not on the "right level" of the down voters neither ! Still, it could be useful for anyone understands it :) – Brewal Aug 26 '13 at 13:58
  • Actually, this one is a lot more simple and doesn't need an array of POST variables. – Funk Forty Niner Aug 26 '13 at 14:27
1

Simple function. You can append required fields array('name', 'age', 'phone')

function checkPost()
{
    if (!$_POST) return false;

    $fields = array('name', 'age');
    foreach ($fields as $field)
    {
        if(!$_POST[$field])
            return false;
    }
    return true;
}

if(checkPost()) { ... }
Bora
  • 10,529
  • 5
  • 43
  • 73