0

I'd like to separate two things.

If a $_POST["something"] was sent, BUT empty.

OR

If a $_POST["something"] was not sent.

Is there a way?

2
  • How do you know if an array HAS a certain key or does not have it? Commented Feb 22, 2012 at 15:03
  • 2
    If a field is empty, it won't appear in the POST Commented Feb 22, 2012 at 15:04

5 Answers 5

3

You might be tempted to use empty(), but it blows up in your face if your possible values include a 0. Best to use something like:

if (isset($_POST['something'])) { // the form field was sent ... if ($_POST['something'] === '') { // the form field was sent, but is empty } } 

This works, as ALL data coming out of the _GET/_POST/_REQUEST superglobals is a string, regardless of whether it's a number or not.

Sign up to request clarification or add additional context in comments.

2 Comments

I advise against using ==='' and for using strlen()
While, in this specific scenario, there may be virtually no difference, it is a better practice to check for a zero-length string based on exactly that - its length and not its content.
2

You'll want to use isset()

if (isset($_POST["something"])){ echo "The Post Variable 'something' was posted"; if (strlen($_POST["something"])==0) echo "The Post Variable is blank"; else echo "The Post Variable Contains ".$_POST['something']; } 

Comments

2

look towards isset and empty.

http://php.net/manual/fr/function.isset.php

http://php.net/manual/fr/function.empty.php

Edit : The comments below are true. Empty should be used for empty strings, not numeric values, float values or a zero in a string​​. However, here's a function if you need to accept these as valid values:

function is_blank($value) { return empty($value) && !is_numeric($value); } 

2 Comments

empty() will not work if the post variable is set to "0" or several other values, according to your link.
empty blows up if your possible data includes a 0. 0 == '' is TRUE, as is $x = 0; empty($x);
0

i use the php function isset() to check if a POST was sent or not

http://php.net/manual/en/function.isset.php

Comments

-1

if ($_POST["something"]) will return true if there is such field

if $_POST["something"] == "" will do the rest

1 Comment

Unreliable: '' == 0 evalutes to TRUE. 0 might be a valid value, and blindly using $_POST['something'] when it isn't set will issue warnings.