Cannot use list as key element

Description

Since PHP 7.1, foreach can destructure the value of each entry with list() (or its short [] syntax): foreach ($array as $key => list($a, $b)). The key part, on the other hand, is always a single target: a variable, a property, or an array offset. It cannot itself be a list() pattern, since a single array key has nothing to be destructured into several variables.

Example

<?php

$array = [['a', 'b'], 'c', 'd'];

foreach ($array as list($key) => $value) {
}

?>

Literal Examples

  • Cannot use list as key element

Solutions

  • Use a plain variable for the key, and only destructure the value with list().

Changed Behavior

This error may appear following an evolution in behavior, in previous versions. See ` <https://php-changed-behaviors.readthedocs.io/en/latest/behavior/.html>`_.