Skip to content

array_chunk return type should take into account the $preserve_keys argument #7277

@gnutix

Description

@gnutix

Feature request

Hello there. While adding some types and types' tests for a wrapper function around array_chunk() in our codebase, I noticed that the return type was always array<array> (not very precise), and it does not account for the $preserve_keys argument.

Example: https://phpstan.org/r/ccba8215-391a-43bf-b0c3-1bd779a1c16c

I'm not sure if this should be fixed using conditional return types or with an extension.

Talking about extensions, I wonder if PHPStan could easily go one step further and be able to infer the specific values of the array (if it is static/known), like below ? (PS: I know it sometimes provides types that are that specific, that's why I think of this, but I don't know how easy it is to do it in this scenario)

$array = [
    'test1' => 'this is test 1',
    'test2' => 'this is test 2',
    'test3' => 'this is test 3',
    'test4' => 'this is test 4',
];
array_chunk($array, 2); // array{0: array{0: 'this is test 1', 1: 'this is test 2'}, 1: array{0: 'this is test 3', 1: 'this is test 4'}}
array_chunk($array, 2, true); // array{0: array{test1: 'this is test 1', test2: 'this is test 2'}, 1: array{test3: 'this is test 3', test4: 'this is test 4'}}

Not sure if it's "that useful" either. Anyway, it's just an idea. 😉

(I don't currently have the time to work on an implementation, but maybe someone will.)

Did PHPStan help you today? Did it make you happy in any way?

(I have a bunch of small issues to create, sorry if I don't come up with something new for each of them 🙏 )

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions