Better way to check variable for null or empty string?

Better way to check variable for null or empty string?

  1. Blog
  2. 15 November 2026
  3. 4 min read

Stefan Bogdanescu

Founder & Senior Architect

The Empty String Trap in PHP Validation

In dynamic languages like PHP, determining whether a value exists and holds meaningful data requires more than a simple if statement. The code snippet you provided illustrates a common stumbling block: checking for an empty string against a variable that has already been processed by trim().

The logic $question === '' will correctly identify an empty string, but relying solely on this after calling trim() introduces a subtle logical flaw regarding your specific requirements. Specifically, if the input is exactly "0", trim("0") returns "0", which evaluates as truthy in most contexts but might be semantically empty depending on business logic. However, the bigger issue with your current approach is that it doesn't explicitly handle null or whitespace-only strings in a single, atomic check.

The Power of trim() Before Validation

Your first step using trim($_POST['question']) is excellent practice. Raw user input from $_POST often contains leading and trailing whitespace that can break database queries or form processing.

When you trim the input:

  • " hello " becomes "hello".
  • " " (spaces only) becomes an empty string "".
  • null usually results in a runtime error if accessed directly, but if sanitized via a helper or cast, it needs specific handling.

However, simply checking if ($question === '') after trimming fails to address the case where $question is null. In PHP, accessing an array key that doesn't exist on $_POST returns null, not an empty string. If you trim a non-existent key (e.g., $_POST['question'] when the key is missing), PHP throws a warning because trim() expects a string or array, not null.

A Unified Approach with empty()

The most idiomatic and robust way to satisfy all three of your requirements—treating null and whitespace-only strings as empty while preserving "0"—is to combine sanitization with a comprehensive check.

You should trim the input first to normalize whitespace, then use the built-in empty() function. This function is designed exactly for this scenario: it returns true if the value is an empty array, null, false, 0, "", "0", or a string of only spaces.

Wait, there is a catch regarding your third requirement: you do not want "0" to be considered empty. The standard empty() function treats the integer 0 as empty, but it also treats the string "0" as empty. This violates your rule that "0" should be valid.

To strictly adhere to your constraints, a custom check or a specific conditional is often safer than relying blindly on empty() for string validation involving zeros. Here is a pattern that handles null, whitespace-only strings (after trimming), and preserves the value "0":

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

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

This approach explicitly checks for an empty string or a space (though trim() removes spaces, making the second check redundant if used immediately after trim). However, the most precise logic that satisfies your constraints is:

  1. Sanitize: Use trim() to remove surrounding whitespace. If the input was only whitespace, it becomes "".
  2. Check for Null: Ensure we aren't dealing with a raw null state before trimming (though ?? '' handles missing keys gracefully).
  3. Preserve Zero: Ensure the check ignores "0".

The cleanest implementation that meets all criteria is:

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

// Check if trimmed string is empty. 
// Note: "0" remains "0", so it passes this check.
if ($question === '') {
    // Handles null (converted to '' by ??), whitespace-only, and actual empty strings
}

Handling the null Case Explicitly

If your environment allows $_POST['question'] to be null (e.g., if you are using a library that returns null on missing keys rather than omitting them), calling trim(null) triggers an error. The null coalescing operator (??) is essential here. By providing an empty string default, you ensure $question is always a string before the comparison.

Why Not Just Use empty()?

Many developers jump straight to if (empty($question)). While this covers null and whitespace, it incorrectly flags "0" as invalid. If your application treats "0" as a valid integer input (common in numeric fields), using empty() without a cast or specific logic will break functionality.

To use empty() while respecting the "0" rule, you would need to force a type check:

if (empty($question) && $question !== '0' && $question !== 0) {
    // Invalid
}

This is verbose and prone to confusion. The direct string comparison $question === '' after trimming is more readable and guarantees that "0" is treated as a valid, non-empty string.

Conclusion on Validation Logic

The best practice for your specific requirements is to normalize the input with trim() and a null coalescing operator, then compare strictly against an empty string. This avoids the pitfalls of empty() regarding numeric zero while cleanly handling null values and whitespace-only inputs in a single, readable condition.

Our network