Blog
Blog
All Articles(https://phpstan.org/blog)
Releases(https://phpstan.org/blog/releases)
Guides(https://phpstan.org/blog/guides)
Other(https://phpstan.org/blog/other)
Other Sections
RSS(https://phpstan.org/rss.xml)
Sponsor PHPStan!(https://phpstan.org/sponsor)
Solving PHPStan error “No value type specified in iterable type”
February 2, 2021 · 5 min read
This problem is reported by PHPStan on level 6(https://phpstan.org/user-guide/rule-levels) when typehinting an array or an iterable object as a parameter type or a return type. It’s there to prevent values of unknown types to be used as a foreach value:
// Function foo() has parameter $items with no value type specified in iterable type array. function foo ( array $items ) : void { foreach ( $items as $item ) { // type of $item is unknown here, static analysis can't find any bugs }
How to solve this error depends on what type has been used.
Arrays #
Solving this for arrays is straightforward - PHPStan needs to know what the array consists of. You can tell PHPStan the types of values and also keys in various ways in PHPDoc:
Type[]
array<Type>
array<int, Type>
non-empty-array<Type>
non-empty-array<int, Type>
An example:
function foo ( array $items ) : void { foreach ( $items as $item ) { // $item is Item }
If you have an array typehint and just want to make this error go away while keeping the possibility of the array holding any type, replace array with mixed[] or array<mixed> .
If your codebase makes use of arrays of various specific shapes(https://phpstan.org/writing-php-code/phpdoc-types#array-shapes) passed around functions and methods, PHPStan can check that the values in specified keys have the correct types. This is different from general arrays that mandate that all the keys and values must be of a specific homogeneous type. Array shapes(https://phpstan.org/writing-php-code/phpdoc-types#array-shapes) allow each key and value to be different.
array{'foo': int, "bar": string}
array{0: int, 1?: int} (key 1 is optional in the array)
array{int, int} (keys are 0 and 1 )
array{foo: int, bar: string} (quotes around array keys aren’t necessary)
Iterable objects #
The error is also reported for these cases:
The typehint is a class that implements Iterator(https://www.php.net/manual/en/class.iterator.php) interface
The typehint is a class that implements IteratorAggregate(https://www.php.net/manual/en/class.iteratoraggregate.php) interface