0

How to fix “Warning: Invalid argument supplied for foreach()” in PHP

Background

If you’re creating an application from ground up, you may already have coded or even designed the core components to check for and avoid non-traversable parameters in some methods or functions that use these variables in foreach statements within them. However, if you are modifying an existing and unfamiliar application you would want to keep the changes localized to avoid affecting other parts of the program. In the case for foreach, a simple check of the arguments can be performed on them before passing to the looping construct.

This article demonstrates how to perform checking on a variable to determine whether it is traversable to not before letting foreach use it.

Software Requirements

  • Windows 7 Professional SP1
  • PHP 5.5.9 / Zend Engine v2.5.0
  • NetBeans IDE 8.0.1

The Codes

Karl San Gabriel

Karl San Gabriel

Java and Enterprise Technologies Expert