Fix for PHP ‘ Warning: Invalid argument supplied for foreach() in …’
February 14th, 2014
Warning: This post is 10 years old. Some of this information may be out of date.
Whilst working on a legacy project* at work I'm getting lots of pages with the PHP warning “Warning: Invalid argument supplied for foreach() in …”. The warning is showing because I like to develop with error reporting turned on.
$items = $product->getFormats();
foreach ($items as $item) {
// ...
}
This code results in a PHP Warning:
Warning: Invalid argument supplied for foreach() in ...
There are a number of solutions for this ranging from turning error reporting off to surpressing the warnings. These have been detailed over on Stackoverflow.
One fix is to check the variable's type first
$items = $product->getFormats();
if (is_array($items)) {
foreach ($items as $item) {
// ...
}
}
This is perfectly valid but I don't like it. This code base is already convoluted, with a mix HTML and PHP closely intertwined with each other*, so adding yet another closing brace 100's of lines down just adds to the complexity.
The solution I prefer is to cast the variable to an array in the loop. This is a lot cleaner, requires less typing and only needs one edit on one line:
$items = $product->getFormats();
foreach ((array) $items as $item) {
// ...
}
}
Unfortunately for me I need to do this quite a few times on this project, but the resulting code will be better for it.
- Unfortunately, budget constraints mean that refactoring our legacy projects just isn't feasible. There are absolutely no tests written and the majority of the projects don't use any kind of structured framework.
Previous →
Can’t find VirtualBox Guest Additions ISO?