PHP, Software Development

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

When we are working with loops, we sometimes need to check first if the variables are iterable. Otherwise, we get the warning message “Warning: Invalid argument supplier for foreach()” in PHP. We get this warning when we use variables are of invalid data type, .e.g., non-iterable.

If you’re creating an application from ground up, you may already have coded or even designed the core components. Some of them check for and avoid non-traversable parameters in some methods or functions. These functions 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 11
  • PHP 5.5.9 / Zend Engine v2.5.0
  • PHP 7, PHP 8
  • NetBeans IDE 8.0.1

PHP 5.5.x foreach Codes to Avoid Invalid Argument

Consider the follow code example.

PHP 7 (PHP 7 >= 7.1.0, PHP 8) built-in is_iterable Function with foreach

When we are using PHP 7 and greater, we could use the built-in is_iteratable function to check if the variables are of valid type before using them in a foreach() statements. Therefore, there is no need to use the is_iterable function on this post for PHP 7 (and greater) when working with foreach().


Got comments or suggestions? We disabled the comments on this site to fight off spammers, but you can still contact us via our Facebook page!.

You Might Also Like