Keys must be of type int|string during array unpacking

Description

Argument unpacking is the transformation of an array into a list of arguments. With arrays, the keys can only be integers or strings: they will be used for positional and named arguments, respectively.

Argument unpacking also applies to iterator and generator. In that case, it is possible to have keys that are not of type integer or string: they might be of any type. Yet, the unpacking of arguments needs these types to understand what kind of arguments is involved.

Any other type is forbidden : null, boolean, float (even without decimal part), and objects with __toString() magic methods. There is not type juggling applied, with or without strict_types directive.

Example

<?php
function foo(...$args) {
    var_dump($args);
}
function gen() {
    yield 1.23 => 123;
    yield '2.34' => 234;
}

try {
    print_r([...gen()]);
} catch (Error $ex) {
    echo 'Exception: ' . $ex->getMessage() . PHP_EOL;
}

?>

Solutions

  • Ensure the iterator yields only integer or string types.

  • Ensure the generator yields only integer or string types.