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
?
2
Answers
Yes, data can be appended to the rows of the original input array directly in the head of a
foreach()
.Details:
&
) -- otherwise there is no indication to modify the original array.null
.Code: (Demo)
Output:
Here is another answer that uses this technique and assigns the reference values via another loop.
Try to modify the original array separately within the loop