skip to Main Content

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


  1. Chosen as BEST ANSWER

    Yes, data can be appended to the rows of the original input array directly in the head of a foreach().

    Details:

    • The new element must be declared by reference (the value must be a variable prepended with &) -- otherwise there is no indication to modify the original array.
    • If the reference variable is not later assigned a value, the default value will be null.

    Code: (Demo)

    $array = [
        ['foo' => 'a', 'bar' => 1],
        ['foo' => 'b', 'bar' => 2],
    ];
    
    foreach ($array as ['new' => &$x, 'bar' => $x]);
    
    var_export($array);
    

    Output:

    array (
      0 => 
      array (
        'foo' => 'a',
        'bar' => 1,
        'new' => 1,
      ),
      1 => 
      array (
        'foo' => 'b',
        'bar' => 2,
        'new' => 2,
      ),
    )
    

    Here is another answer that uses this technique and assigns the reference values via another loop.


  2. Try to modify the original array separately within the loop

        $array = [
            ['foo' => 'a', 'bar' => 1],
            ['foo' => 'b', 'bar' => 2],
        ];
        
        foreach ($array as &$row) {
            $row['new'] = 'your_new_value';
        }
        
        // It's important to unset the reference to $row to avoid any unexpected behavior later.
        unset($row);
        
        // Now $array has a new key 'new' in each row.
        print_r($array);
    
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search