Since PHP7.1, a foreach() expression can implement array destructuring as a way of unpacking row values and make individualized variable assignments for later use.
When using array destructuring within the head/signature of a foreach() loop, can new elements be declared instead of merely being accessed?
For example:
$array = [
['foo' => 'a', 'bar' => 1],
['foo' => 'b', 'bar' => 2],
];
Can I append a new element to each row of the original array with the key new?
Yes, data can be appended to the rows of the original input array directly in the head of a
foreach().A general benefit of using array destructuring is the ability to specifically access/isolate data within a given array without loading unneeded data into a variable.
Details:
&) -- otherwise there is no indication to modify the original array.null.Code: (Demo)
Output:
Using the above sample input array, a body-less loop can be used to assign the first level keys as a new column in the array without declaring the full row as a reference. Code: (Demo)
This approach requires one less globally-scoped variable to be declared versus:
and if not modifying by reference, the
foreach()signature's required value variable isn't even used.Output (from all):
Here is another answer that uses this technique and assigns values to the reference variables via another loop.
@Dharman mentioned in a PHP internals thread that array destructuring without a
foreach()executes the same behavior. DemoAlthough no longer supported, it was recommended that I clarify that for PHP7.1 through PHP7.2, this technique will cause a fatal error.