fishmong3r fishmong3r - 7 months ago 13
PHP Question

Add new "col" to an existing two-dimensional array

I have a two-dimensional array:

$arr= array();
array_push($arr, array('col1' => 'someval', 'col2' => 'someval'));
array_push($arr, array('col1' => 'someval', 'col2' => 'someval'));


Now I want to add a new "col" to each 2nd level array like
'col3' => 'someval'
. How to do that?

Answer

Use [] notation to add a value with key key:

foreach ($arr as &$item) { 
    $item['col3'] = 'value'; 
}

Use & with $item so as pass each array of $arr by reference.

Comments