Why This Happens
The foreach construct requires an array or an object implementing Traversable. When a variable is null, false, or a scalar type, foreach cannot iterate over it. This often happens when a function that normally returns an array returns null or false on failure.
The Problem
$users = fetchUsers(); // Returns null on failure
foreach ($users as $user) {
echo $user['name'];
}The Fix
$users = fetchUsers() ?? [];
foreach ($users as $user) {
echo $user['name'];
}Step-by-Step Fix
- 1
Check the variable type
Add var_dump() before the foreach to see what type the variable actually is.
- 2
Trace the data source
Find where the variable is assigned and check if the function can return null, false, or a non-array value.
- 3
Default to empty array
Use the null coalescing operator ?? [] to default to an empty array, or add an is_array() check before the foreach.
Bugsly catches this automatically
Bugsly's AI analyzes this error pattern in real-time, explains what went wrong in plain English, and suggests the exact fix — before your users even report it.
Try Bugsly free