Skip to content

Array element types are lost with array_chunk #3498

@adam-openplay

Description

@adam-openplay

Describe the bug
When passing an array through array_chunk, intelephense loses the knowledge of the type of the array elements.

To Reproduce

$example = ['foo' => 0.1, 'bar' => 0.2, 'baz' => 0.3, 'quz' => 0.4];

foreach (array_chunk($example, 2, true) as $chunk) {
    // intelephense reports the type of `$chunk` as `mixed`
}

Expected behavior
In the example above, I'd expect intelephense to know that $chunk is in fact array<string, float>.

I believe this could be achieved by tweaking the stub as follows:

/**
 * Split an array into chunks
 * @link https://php.net/manual/en/function.array-chunk.php
 * @template TKey of int|string
 * @template TValue
 * @param array<TKey, TValue> $array <p>
 * The array to work on
 * </p>
 * @param int $length <p>
 * The size of each chunk
 * </p>
 * @param bool $preserve_keys [optional] <p>
 * When set to true keys will be preserved.
 * Default is false which will reindex the chunk numerically
 * </p>
 * @return array<int, array<TKey|int, TValue>> a multidimensional numerically indexed array, starting with zero,
 * with each dimension containing size elements.
 */
#[Pure]
function array_chunk(array $array, int $length, bool $preserve_keys = false): array {}

The TKey|int thing is a bit weird thanks to the $preserve_keys argument, but otherwise this seems to work.

Platform and version
Neovim v0.11.5
Ubuntu 24.04
Intelephense 1.16.3

Metadata

Metadata

Assignees

No one assigned

    Labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions