Cannot unpack array with string keys

The problem is that the splat operator (array unpacking operator or ...) does not work with associative arrays. Example:

$array = [1, 2, 3];
$assoc = ["one" => 1, "two" => 2, "three" => 3];

var_dump(...$array); //Works
var_dump(...$assoc); //Doesn't work

You need to force an array to be numerically indexed in order to unpack it. You do this using array_values:

$values = array_values($q->fetch());
ModelController::execute(...$values);

Array values will ensure all values have a sequential numeric key.

Update

Starting PHP 8 there will be support for named arguments which will make both cases work. An example is documented in the proposed RFC for named arguments which says the following code should work starting PHP 8

$params = ['start_index' => 0, 'num' => 100, 'value' => 50];
array_fill(...$params);

Update PHP 8.1

Since PHP 8.1, unpacking arrays also works with string-key arrays, so the error FATAL ERROR Uncaught Error: Cannot unpack array with string keys will not be applicable anymore.

Example:

$array1 = ["a" => 1];
$array2 = ["a" => 2];
$array = ["a" => 0, ...$array1, ...$array2];
var_dump($array); // ["a" => 2]

RFC: PHP RFC: Array unpacking with string keys


If you got this error when you tried to unpack an associative array into another array then you can use array_merge instead:

<?php

$inner = ["b" => "i", "c" => "i"];
$outer = ["a" => "o", "c" => "o"];

var_dump(array_merge($outer, $inner));
var_dump(array_merge($inner, $outer));

will produce

array(3) {
  ["a"]=>
  string(1) "o"
  ["c"]=>
  string(1) "i"
  ["b"]=>
  string(1) "i"
}

array(3) {
  ["b"]=>
  string(1) "i"
  ["c"]=>
  string(1) "o"
  ["a"]=>
  string(1) "o"
}

Tags:

Php

Arrays