Menu

← Back to foreach.*

Error Identifier: foreach.nonIterable

Every error reported by PHPStan has an error identifier. Here’s a list of all error identifiers. In PHPStan Pro you can see the error identifier next to each error and filter errors by their identifiers.

Code example #

<?php declare(strict_types = 1);

function process(string $data): void
{
    foreach ($data as $char) {
        echo $char;
    }
}

Why is it reported? #

The expression passed to foreach is not an iterable type. PHP’s foreach only works with arrays, objects implementing Traversable, or other iterable types. Passing a non-iterable value will produce a runtime warning.

How to fix it #

Convert the value to an iterable type, or ensure the variable has the correct type:

 <?php declare(strict_types = 1);
 
-function process(string $data): void
+function process(string $data): void
 {
-    foreach ($data as $char) {
+    foreach (str_split($data) as $char) {
         echo $char;
     }
 }

Or fix the parameter type if it should be an array:

 <?php declare(strict_types = 1);
 
-function process(string $data): void
+/** @param list<string> $data */
+function process(array $data): void
 {
     foreach ($data as $char) {
         echo $char;
     }
 }

How to ignore this error #

You can use the identifier foreach.nonIterable to ignore this error using a comment:

// @phpstan-ignore foreach.nonIterable
codeThatProducesTheError();

You can also use only the identifier key to ignore all errors of the same type in your configuration file in the ignoreErrors parameter:

parameters:
	ignoreErrors:
		-
			identifier: foreach.nonIterable

Rules that report this error #

  • PHPStan\Rules\Arrays\IterableInForeachRule [1]

Edit this page on GitHub

Theme
A
© 2026 PHPStan s.r.o.