Fix "Invalid argument supplied for foreach" in PHP & Laravel

Fix "Invalid argument supplied for foreach" in PHP & Laravel

Modified
Nov 23, 2022
Written by
Benjamin Crozat
0
comments
2 minutes
read

Why does the “Invalid argument supplied for foreach()” warning occurs?

The “Invalid argument supplied for foreach()” warning occurs when you try to iterate over something other than an array or an object.

On PHP 8+, the warning has been rewritten to “foreach() argument must be of type array|object”.

Whatever version of PHP you’re on, you need to ensure that an array or an object is always passed to foreach.

Use the null coalescing operator

When you cannot be certain that you’ll get an array or null, you can use the null coalescing operator to ensure an array will always be passed to foreach.

foreach ($value ?? [] as $item) {
    …
}

Check if your value is iterable

One of the safest way to go is to use the is_iterable() function. It checks for either:

if (is_iterable($value)) {
    foreach ($value as $item) {
	    …
    }
}

Use Laravel’s collections

If you’re using Laravel, you can use collections to wrap your arrays and work with safer code.

Let’s say you’re refactoring a poor-quality codebase and have to deal with uncertain return values. Wrapping the return value in the collect() helper will ensure that you always get an iterable to loop over.

// The safe collect() helper.
$items = collect(
    // The unsafe method.
    $foo->getItems()
);

// Looping over $items will always work.
foreach ($items as $item) {
    //
}

Of course, since you’re using Laravel’s collections, you could refactor to their built-in methods:

$items = collect(
    $foo->getItems()
);

$items->each(function ($item) {
    //
});
About Benjamin Crozat
Benjamin Crozat

Hi! I’m from the South of France and I’ve been a self-taught web developer since 2006. When I started learning PHP and JavaScript, PHP 4 was still widely used, Internet Explorer 6 ruled the world, and we used DHTML to add falling snow on websites.

Being able to educate myself for free on the web changed my life for the better. Giving back to the community was a natural direction in my career and I truly enjoy it.

Therefore, I decided to take action:

  1. I launched this blog in September 2022 with the goal to be in everyone’s Google search. I get more than tens of thousands of monthly clicks from it and even more visits overall (my analytics dashboard is public by the way).
  2. I also started growing my X (formerly Twitter) account at the same time, which has now over 7,000 followers.
  3. All the content I write is free thanks to my sponsors.

I also want to be completely free with my time and make a living with my own products. In April 2024, I launched Nobinge, a tool to summarize and chat with your content, including YouTube videos.

Believe me, I’m just getting started!

0 comments

You need to be signed in to comment this post.
Sign in with GitHub