cleanest way to skip a foreach if array is empty

cleanest way to skip a foreach if array is empty

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

Stefan Bogdanescu

Founder & Senior Architect

The Empty Array Problem in PHP Foreach Loops

The pattern of guarding a foreach loop with an if(!empty($array)) block is so common it often feels like good practice, but upon closer inspection, it usually signals a misunderstanding of how PHP handles iteration over empty collections. When you write:

$items = [];

if (!empty($items)) {
    foreach ($items as $item) {
        print $item;
    }
}

You are technically correct in that the foreach construct itself will not throw an error if $items is empty. The loop simply does not execute its body, and execution proceeds normally. However, this approach introduces unnecessary nesting and cognitive load. It forces the reader to mentally parse two layers of logic ("Is there data? If so, process it") rather than one clean layer ("Iterate over whatever exists").

The desire to avoid this nesting often stems from a specific misconception: that foreach might throw an error on empty arrays in certain contexts or versions. In standard PHP, iterating over an empty array is perfectly safe. The real issue is code clarity. Removing the conditional check flattens the logic and adheres to the principle of doing less work to achieve the same result.

Why the Guard Clause is Usually Unnecessary

The primary reason developers add if (!empty($array)) checks before a loop is fear of side effects. If your loop body contains operations that are expensive or have significant state changes, you might want to ensure there is data before entering them. However, if the cost of iterating over zero items is negligible—and it almost always is—then the check is dead code.

Consider a scenario where $items comes from a database query that returns no results. If your loop body simply renders HTML or processes data:

foreach ($items as $item) {
    renderItem($item);
}

If $items is empty, renderItem is never called. This is the intended behavior for a rendering loop; you don't want to render nothing if there's nothing to render. The if statement adds no safety here, only noise. It suggests that an error could occur without data, which contradicts the reality of the language runtime.

The Error Suppression Myth

You mentioned using the @ error suppressor as an alternative. While PHP does allow you to suppress errors like this:

foreach (@$items as $item) { // Intentionally incorrect syntax for suppression
    print $item;
}

It is important to clarify that @ only suppresses errors and warnings, not exceptions. If your loop body throws an Exception, it will still crash the script regardless of whether the array is empty or not. Furthermore, using @ is a code smell in modern PHP development because it hides bugs rather than fixing them. It makes debugging significantly harder by silencing potential issues that developers need to know about during testing.

If you are worried about the performance cost of checking empty() versus just looping, benchmarks consistently show that the overhead of an empty check is negligible compared to the actual work done inside a loop containing thousands of items. Therefore, removing the check does not hurt performance; it only improves readability.

Handling Side Effects and Early Returns

There are specific architectural patterns where you do want to know if an array is empty without nesting, but doing so requires restructuring the logic rather than adding guards.

If your code needs to behave differently when no items exist—such as returning null instead of rendering a list—you should handle that in the calling context or within the function itself, not inside the loop guard. For example:

function renderList(array $items): void {
    if (empty($items)) {
        return; // Or throw an exception, or render a fallback message
    }

    foreach ($items as $item) {
        renderItem($item);
    }
}

Here, the if statement is not guarding the loop to prevent an error. It is defining the contract of the function: "If there is no data, do nothing (or handle the empty state explicitly)." This is distinct from the pattern where the check exists solely to avoid iterating over zero items.

Conclusion on Best Practices

The cleanest way to skip a foreach if an array is empty is simply to remove the if statement entirely. PHP's foreach loop is robust; it handles empty arrays gracefully by executing zero iterations. By stripping away the guard clause, you reduce nesting levels, eliminate dead code paths, and make your intent clearer: "Process every item in this collection."

This approach aligns with modern PHP practices where explicit error suppression (@) is discouraged in favor of clear control flow. If an empty array causes a logical issue in your application, that is a design problem to be solved by returning early or handling the empty state explicitly, not by adding redundant checks around standard language constructs.

For developers working within the Laravel ecosystem, this principle holds true regardless of version. Whether you are using Laravel 9, 10, or 11, the underlying PHP engine behaves consistently regarding array iteration. If you need to handle nullability or optional collections in a more robust way, consider utilizing Laravel's collection helpers which provide methods like count() or isEmpty() that can be chained cleanly if your architecture demands explicit state checks before processing. However, for standard arrays, trust the language and iterate directly.

Our network