Fix for PHP ‘ Warning: Invalid argument supplied for foreach() in …’

Posted by Andrew McCombe on Fri Feb 14, 2014

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.

This code results in a PHP Warning:

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

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:

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.