Invalid argument supplied for foreach()

Invalid argument supplied for foreach()

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

Stefan Bogdanescu

Founder & Senior Architect

Invalid argument supplied for foreach()

You've likely encountered this specific PHP warning while iterating over dynamic data: Warning: Invalid argument supplied for foreach(). It usually appears when a function that is supposed to return an array sometimes returns null or another non-array type. Consider a scenario where $values = get_values() might yield an empty result, and your subsequent loop fails immediately because foreach strictly requires an iterable array.

If you cannot refactor the upstream logic—perhaps due to backward compatibility constraints, lack of access to the source code, or legacy system limitations—you need a reliable guard without sacrificing performance or readability. Below are the standard approaches, their trade-offs, and which one fits different contexts best.

Type Casting with (array)

The most concise syntax is casting the variable to an array:

$values = get_values() ?? []; 
foreach ($values as $value) {
    // ...
}

Or simply:

foreach ((array) get_values() as $value) {
    // ...
}

Casting null to an array results in an empty array ([]). This preserves the original variable reference and keeps the loop body clean. It is efficient because casting is a lightweight operation, and it avoids adding branches or conditionals inside the loop logic. The downside is that if $values contains something else entirely (e.g., a string), casting will wrap it in an array as ['string'], which might mask logical errors elsewhere if not checked before use.

Explicit Initialization with ?? []

Using the null coalescing operator is often preferred in modern PHP versions (7.4+) for its clarity:

$values = get_values() ?? [];
foreach ($values as $value) {
    // ...
}

This approach explicitly declares that if get_values() returns null, we default to an empty array. It makes the intent clear to future maintainers: "we expect this to be iterable, and here's our fallback." If get_values() returns a string or integer instead of null, the warning still occurs unless you also handle non-null non-arrays. For strict type safety in newer PHP versions, consider using union types if available:

function getValues(): array|null { ... }

But if you're constrained by older versions, sticking to ?? [] is safe and idiomatic.

Conditional Wrapping with if (is_array())

Another common pattern is wrapping the loop in a conditional check:

$values = get_values();
if (is_array($values)) {
    foreach ($values as $value) {
        // ...
    }
}

This approach avoids modifying the variable and instead guards the iteration logic. It's useful when you want to distinguish between "no data" and "invalid data." However, it adds nesting and can clutter control flow if overused. Performance-wise, is_array() is negligible for most applications, but readability suffers slightly compared to casting or null coalescing.

Trade-offs and Best Practices

The choice depends on your environment and coding standards:

  • Casting (array) is minimal and works everywhere, even in older PHP versions.
  • Null coalescing ?? [] is clearer and more expressive in modern PHP (7.4+).
  • Conditional checks are best when you need to react differently based on whether data exists or not.

If the function could return unexpected types beyond null, consider adding validation:

$values = get_values() ?? [];
if (!is_array($values)) {
    // handle error or log warning
}

This prevents silent failures where non-array data gets wrapped unintentionally. In Laravel projects, you might leverage collections for safer iteration:

$collection = collect(get_values());
foreach ($collection as $value) {
    // ...
}

Collections handle null gracefully and offer a functional API that reduces boilerplate. While slightly more overhead than raw arrays, they improve code safety in complex pipelines.

Ultimately, if you can't change the source function, initializing with an empty array via ?? [] or casting is the cleanest path forward. Choose based on your PHP version and whether distinguishing between "empty" and "invalid" matters for your use case.

Our network