225

Since PHP is a dynamic language what's the best way of checking to see if a provided field is empty?

I want to ensure that:

  1. null is considered an empty string
  2. a white space only string is considered empty
  3. that "0" is not considered empty

This is what I've got so far:

$question = trim($_POST['question']);

if ("" === "$question") {
    // Handle error here
}

There must be a simpler way of doing this?

2
  • 3
    I would say to use empty($question), but that also considers 0 to be empty. Commented Dec 19, 2008 at 16:06
  • 1
    I wish I knew a code that is simpler than just a basic condition. Commented Jul 30, 2023 at 13:49

9 Answers 9

360

Function for basic field validation (present and neither empty nor only white space

function IsNullOrEmptyString(string|null $str){
    return $str === null || trim($str) === '';
}
Sign up to request clarification or add additional context in comments.

1 Comment

Since OP is asking for a 'simpler' version of an extremely simple operation, I'm going to say that 'better' is what's actually warranted.
130
if (strlen($str) == 0){
    // do whatever
}

Replace $str with your variable. NULL and "" both return 0 when using strlen.

Since PHP 8.1 passing NULL to strlen() will cause a depreciation notice. https://3v4l.org/0s1Gs If you know the variable type to be either string or null then you can check it as so:

if ($str === null || strlen($str) == 0){
    // do whatever
}

8 Comments

And there's always: if(strcmp('', $var) == 0)...
Why ==0 and not just if (strlen($str)) ?
@Noumenon Because that would impair readability without solving anything. It is real easy to read your suggestion as "if there is a length" while it (of course) means the opposite.
Will not help for string with spaces only, if someone cares for that
If the variable is not set, this will produce a warning
|
29

Use PHP's empty() function. The following things are considered to be empty

"" (an empty string)
0 (0 as an integer)
0.0 (0 as a float)
"0" (0 as a string)
NULL
FALSE
array() (an empty array)
$var; (a variable declared, but without a value)

For more details check empty function

2 Comments

Poster said that they DON'T want to consider "0" empty
@dougd_in_nc The purpose of SO is that questions are meant to be as generic as possible to build a knowledge base, and there are much more people - like myself - coming into this question from Google who don't have all of the original poster's requirements. For those people, this is the right answer and doesn't deserve the downvotes it has.
20

I'll humbly accept if I'm wrong, but I tested on my own end and found that the following works for testing both string(0) "" and NULL valued variables:

if ( $question ) {
  // Handle success here
}

Which could also be reversed to test for success as such:

if ( !$question ) {
  // Handle error here
}

3 Comments

may I suggest "if (trim($n)).." otherwise if a $_POST var (for example) is simply " ", it would be considered valid, whereas, in most cases this is as good as an empty string
If " " is not an acceptable value for a specific function, then using trim would be a great idea.
This will return false for "0", numeric 0 or 0.0, and FALSE.
8

I'd recommend using the null coalescing operator. This will also supress an error in the case that the array key does not exist.

if (trim($_POST['question'] ?? '') === '') {
    // Handle error here
}

1 Comment

This is also good practice for non-array variables, since passing passing null to string functions like trim() will throw an error in all modern versions of PHP.
6

Beware false negatives from the trim() function — it performs a cast-to-string before trimming, and thus will return e.g. "Array" if you pass it an empty array. That may not be an issue, depending on how you process your data, but with the code you supply, a field named question[] could be supplied in the POST data and appear to be a non-empty string. Instead, I would suggest:

$question = $_POST['question'];

if (!is_string($question) || ($question = trim($question))) {
    // Handle error here
}

// If $question was a string, it will have been trimmed by this point

2 Comments

Id say if you get an array where you expected a string it should be an error. If you expect an array then you should have a separate filtering function for that.
Isn't that code treating it as an error? If filtering is done elsewhere, care would have to be taken that it's not duplicating knowledge of the args' validation rules into separate places.
0

There is no better way but since it's an operation you usually do quite often, you'd better automatize the process.

Most frameworks offer a way to make arguments parsing an easy task. You can build you own object for that. Quick and dirty example :

class Request
{

    // This is the spirit but you may want to make that cleaner :-)
    function get($key, $default=null, $from=null)
    {
         if ($from) :
             if (isset(${'_'.$from}[$key]));
                return sanitize(${'_'.strtoupper($from)}[$key]); // didn't test that but it should work
         else
             if isset($_REQUEST[$key])
                return sanitize($_REQUEST[$key]);

         return $default;
    }

    // basics. Enforce it with filters according to your needs
    function sanitize($data)
    {
          return addslashes(trim($data));
    }

    // your rules here
    function isEmptyString($data)
    {
        return (trim($data) === "" or $data === null);
    }


    function exists($key) {}

    function setFlash($name, $value) {}

    [...]

}

$request = new Request();
$question= $request->get('question', '', 'post');
print $request->isEmptyString($question);

Symfony use that kind of sugar massively.

But you are talking about more than that, with your "// Handle error here ". You are mixing 2 jobs : getting the data and processing it. This is not the same at all.

There are other mechanisms you can use to validate data. Again, frameworks can show you best pratices.

Create objects that represent the data of your form, then attach processses and fall back to it. It sounds far more work that hacking a quick PHP script (and it is the first time), but it's reusable, flexible, and much less error prone since form validation with usual PHP tends to quickly become spaguetti code.

1 Comment

You did the exact opposite of what he wanted... simplicity.
0

This one checks arrays and strings:

function is_set($val) {
  if(is_array($val)) return !empty($val);

  return strlen(trim($val)) ? true : false;
}

1 Comment

Not bad. The answer by PHPst does the same but more concisely though.
-1

When you want to check if a value is provided for a field, that field may be a string , an array, or undifined. So, the following is enough

function isSet($param)
{
    return (is_array($param) && count($param)) || trim($param) !== '';
}

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.