PHP: if !empty & empty

PHP: if !empty & empty

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

Stefan Bogdanescu

Founder & Senior Architect

PHP: if !empty & empty Logic Patterns

Validating form inputs often involves more than just checking if a string exists. You frequently need to enforce conditional logic where one field's presence dictates another, or where you must explicitly reject scenarios where specific combinations are invalid. The source material presents a common scenario: validating a "Youtube" field and a "link" field.

The initial approach uses if(!empty($youtube)) to ensure the YouTube URL is present before checking if it matches the expected format. This prevents false positives from malformed strings like "123". However, the logic quickly becomes complex when you need to cross-reference multiple fields. The developer attempts to combine these checks using logical operators:

if(!empty($youtube) && empty($link)) {
    if ($pos === false) { 
        echo "Du skal indtaste youtube et URL...";
        echo "<a href='javascript:history.back();'>GÃ¥ tilbage</a>";
    }
}

This block specifically targets the case where a user has selected a YouTube video but failed to provide an alternative link. While this works, it reveals a critical limitation in PHP's empty() function and how boolean logic interacts with it. Understanding these nuances is essential for robust validation.

The Trap of empty() and Type Juggling

The core complexity here lies in how PHP evaluates truthiness. The empty() construct returns true for an empty string (""), a null value, the integer 0, and the float 0.0. However, it does not return true for a string containing only whitespace unless that whitespace is trimmed first.

When combining checks like !empty($youtube) and empty($link), you are relying on PHP's loose typing rules. If $link contains a string with spaces (e.g., " "), empty() returns false, meaning the validation passes even if the user didn't intend to submit a link. This is a common pitfall when migrating from languages like JavaScript or Java where strict equality checks are the norm.

To handle this correctly, you must decide if whitespace constitutes valid data. If not, you should trim the input before checking:

$trimmedLink = trim($link);
if (!empty($trimmedLink)) {
    // Treat as valid link
}

Handling the Opposite Condition

The source material asks how to check for the opposite: a scenario where "there's something in LINK and nothing in youtube." In logic terms, you are looking for !empty($link) && empty($youtube).

This is structurally identical to the previous example but with the operands swapped. The implementation pattern remains consistent:

if (!empty($link) && empty($youtube)) {
    // Logic for when Link exists but YouTube is missing
}

The trade-off here is user experience. If a field is optional, you might want to allow empty($youtube) even if $link is present. However, if your business logic requires that if a user provides a link, they must also provide a YouTube ID (perhaps for internal tracking), then this condition becomes a mandatory error state.

Checking for Total Absence

The final question addresses checking if there is "nothing at all in those two." This implies both fields are effectively empty. In PHP, you can chain the empty() checks:

if (empty($youtube) && empty($link)) {
    // Both fields are considered empty
}

However, be wary of relying solely on empty() for this check if one of your fields is legitimately expected to be 0 or an empty string as a default state. For instance, if $link is supposed to contain a numeric ID like 0, empty($link) will return true, potentially triggering the "nothing at all" logic incorrectly. In such cases, casting to string before checking or using strict comparison (===) against an empty string provides more precision.

Refactoring with Laravel

If you are working within the Laravel ecosystem, handling these raw validation checks in your controller is generally discouraged. The framework provides a robust validator that abstracts away the empty() nuances and offers expressive rules for conditional logic.

Instead of writing nested if statements like those in the source material, you can define validation rules in your form request or controller method:

use Illuminate\Validation\Validator;

$validator = Validator::make($request->all(), [
    'youtube' => ['required_without:link', 'string'],
    'link' => ['required_without:youtube', 'string'],
]);

if ($validator->fails()) {
    return redirect()->back()
        ->withErrors($validator)
        ->withInput();
}

The required_without rule elegantly handles the "check if something in Link and nothing in Youtube" logic without manually inspecting the variables. This approach is safer, more readable, and less prone to the type-juggling errors inherent in raw PHP checks. For projects requiring complex conditional validation, exploring Laravel's validation documentation or resources from LaravelCompany can provide further patterns on implementing these rules effectively.

Ultimately, while raw if statements offer granular control over specific error messages (like the Danish text in the source), leveraging a framework's validator ensures your application handles edge cases like whitespace and type coercion consistently across your entire codebase.

Our network