How to Fix “Invalid Argument Supplied for foreach()” in PHP

How to Fix “Invalid Argument Supplied for foreach()” in PHP

🔥 Problem Example:
<?php
$data = null; // or could be a variable not set or not an array

foreach ($data as $item) { // Warning: Invalid argument supplied for foreach()
echo $item;
}
?>
❓ Why This Happens
The PHP warning:
E_WARNING: Invalid argument supplied for foreach()
means that the variable you're passing into foreach() is not iterable. This happens if the variable is:

null

a string

not defined

not an array or Traversable object

✅ Correct Code Example (Fix):
<?php
$data = ['apple', 'banana', 'orange']; // ✅ Valid array

foreach ($data as $item) {
echo $item . "<br>"; // ✅ Works perfectly
}
?>
🧠 Final Note from TopSourceCode:
✅ The “Invalid argument supplied for foreach()” warning in PHP is very common.
Always ensure that your variable is an array or iterable object before using foreach() to avoid this issue.

Back