Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unable to add new fields to array within foreach

I have a 2-dimensional array:

$test = array(
    "foo" => array(
        'a' => 1,
        'b' => 2,
        'c' => 3
    ),
    "bar" => array(
        'a' => 1,
        'b' => 2,
        'c' => 3
    ),
    "baz" => array(
        'a' => 1,
        'b' => 2,
        'c' => 3
    )
);

I would like to add a field named 'd' with the value 4 to each element of the outer array, so that the resulting array becomes:

array(
    "foo" => array(
        'a' => 1,
        'b' => 2,
        'c' => 3,
        'd' => 4
    ),
    "bar" => array(
        'a' => 1,
        'b' => 2,
        'c' => 3,
        'd' => 4
    ),
    "baz" => array(
        'a' => 1,
        'b' => 2,
        'c' => 3,
        'd' => 4
    )
)

I've tried this:

foreach ( $test as $elem ) 
{
    $elem['d'] = 4;
}

which doesn't work. What am I doing wrong, and how can I make this work?

like image 454
Šime Vidas Avatar asked Oct 31 '12 00:10

Šime Vidas


2 Answers

Arrays and primitives are passed by value in PHP (though objects are passed by reference). One method to overcome this in a foreach loop is to access the subarrays by reference in the loop:

// Call $elem by reference with &
foreach ( $test as &$elem ) {
    $elem['d'] = 4;
}

print_r($test);
array(3) {
  ["foo"]=>
  array(4) {
    ["a"]=>
    int(1)
    ["b"]=>
    int(2)
    ["c"]=>
    int(3)
    ["d"]=>
    int(4)
  }
  ...
}
like image 113
Michael Berkowski Avatar answered Oct 29 '22 02:10

Michael Berkowski


$test = array(
    "foo" => array(
        'a' => 1,
        'b' => 2,
        'c' => 3
    ),
    "bar" => array(
        'a' => 1,
        'b' => 2,
        'c' => 3
    ),
    "baz" => array(
        'a' => 1,
        'b' => 2,
        'c' => 3
    )
);

foreach($test as $key => $val)
    $test[$key]['d'] = 4;

print_r($test);
like image 31
Ezequiel Villarreal Avatar answered Oct 29 '22 01:10

Ezequiel Villarreal