PHP warning: invalid argument supplied for foreach()

Fix for PHP Warning – Invalid argument supplied for foreach() in wordpress plugin php, symfony, codeigniter, laravel and yii2 or other PHP programming languages.

While working on a WordPress, PHP, Laravel, yii2, codeigniter, symfony or any other application, I got a PHP warning.

How to Solve PHP warning: invalid argument supplied for foreach()?

Warning: Invalid argument supplied for foreach() in …

I can simply hide warnings in PHP server side languages. But I like to know advance all about such simple fix issue for “invalid argument supplied for foreach() in” matters in deep.

Actually this error code is coming from a foreach loop. I just try to print the php variable like as a var_dump() values in an array using this foreach loop.

foreach ($products as $product) {
 // ...

In the PHP manual, it says that

The PHP Loop construct supported an easy way to PHP Loop foreach iterate over arrays. foreach works only on arrays and objects, and will issue an error code when you try to use it on a variable with a different data type or an uninitialized variable. and php get a “warning: invalid argument supplied for foreach() in”.

This is the basic cause behind this warning. I am passing something to foreach loop that is not an array.

To resolved this warning, I have two simple options at here.

Solution 1

I can check the type of that PHP variable & if it is an array, then only pass it to the foreach loop.

if (is_array($products)) {
 foreach ($products as $product) {
 // ...

Now I ensure that I have an array for foreach loop.

Solution 2

I can also resolved this warning by cast that PHP variable to an array in the loop. This is a lot cleaner, requires less typing as well as only required single edit on a single line.

foreach ((array) $products as $product) {
 // ...

If I cast any value to an array, I will get an array whatever value it was.

Fixing the “invalid argument supplied for foreach()” PHP error

Consider the source code PHP snippet below:

This Best 100% working solution is display in the source code below: invalid argument supplied for foreach() in

Web Programming Tutorials Example with Demo

Read :


You can also read about AngularJS, ASP.NET, VueJs, PHP.

I hope you get an idea about warning: invalid argument supplied for foreach() wordpress.
I would like to have feedback on my blog.
Your valuable feedback, question, or comments about this article are always welcome.
If you enjoyed and liked this post, don’t forget to share.

Leave a Comment