Solve error - invalid argument supplied for foreach() PHP

The warning “invalid argument supplied for foreach()” appears when the data you pass to the construct is not an array or object.

The PHP foreach function is used to iterate over arrays. It will issue a warning when you pass a non-array type as shown below:

$name = "Nathan";

// 👇 passing string into foreach causes warning
foreach ($name as $n) {

Since the $name variable is a string type, the code above will produce the following warning:

Warning: Invalid argument supplied for foreach() in ...

There are two ways you can make this warning disappear:

Let’s see how you can do both next.

Put foreach inside an if block

The easiest way to solve this warning is to add an if check before calling foreach

You need to check if the variable is an array or object like this:

// 👇 check if the values is an array or object
if (is_array($values) || is_object($values)) {
    // 👇 call foreach inside the if statement
    foreach ($values as $value) {

When the is_array() and is_object() check both returns false, the if block will be skipped, so the foreach won’t be called.

This way, you ensure foreach is only called with a variable that’s either an array or object type.

Cast the variable into an array

You can cast the variable you put as the foreach parameter into an array with the following code:

foreach ((array) $values as $value) {

By casting the $values into an array, foreach will be able to iterate over the variable.

While this is a valid option to resolve the warning, keep in mind that PHP will produce an “Undefined variable” warning when the variable has not been set before.

It’s not an issue if you know that an array will always be returned. But if you want to make sure the variable is declared using an isset check:

if (isset($values)) {
    foreach ((array) $values as $value) {

Sometimes, the “invalid argument supplied for foreach()” warning still appears when you pass a multi-dimensional array.

Using the isset and array casting as shown above will help you resolve the warning for multi-dimensional arrays.

Take your skills to the next level ⚡️

I'm sending out an occasional email with the latest tutorials on programming, web development, and statistics. Drop your email in the box below and I'll send new stuff straight into your inbox!

No spam. Unsubscribe anytime.