Skip to content

Array<string, ...> is not reliable if a numeric string makes it in #6847

@leongersen

Description

@leongersen

Bug report

The type system does not account for PHP converting numeric strings to integers in array keys.

This isn't necessarily a "bug" in PhpStan, but the result of how arrays work in PHP.

https://www.php.net/manual/en/language.types.array.php

Additionally the following key casts will occur:

Strings containing valid decimal ints, unless the number is preceded by a + sign, will be cast to the int type. E.g. the key "8" will actually be stored under 8. On the other hand "08" will not be cast, as it isn't a valid decimal integer.

If an (unexpected) numeric string is used as the key in an array, PHP will cast it to an int. Static analysis does not take this into account,.

Code snippet that reproduces the problem

In this example, all code is correctly typed, and PhpStan dumps string for the array key type. When running the code, however, the type is an integer.

https://phpstan.org/r/0168ad9a-f3ed-486b-8ec6-3602cc0881d1

Expected output

I'm not sure what I'd like reported here. If I pass $text in the example to a function with a string argument type hint and strict_types=1, this does result in a TypeError. If I cast $text to (string) first, which seems to be the correct fix here, PhpStan "incorrectly" reports Casting to string something that's already string.. For what it's worth, other tooling such as EA Extended also reports the cast as redundant.

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions