PHP Arrays: How to add 'key & value' to an existing array

Deepak Keynes picture Deepak Keynes · May 20, 2016 · Viewed 13.4k times · Source

I do not know how to add a key and value to the existing array. My array goes like this. Initially I have tried adding using array_push() but it added not as I needed it.

I have given my output after I gave the 'var_dump'.

array (size=6)
  0 => 
    array (size=3)
     'id' => int 7
      'title' => string 'Pongal' (length=6)
      'start' => string '2016-05-16' (length=10)
  1 => 
    array (size=3)
       'id' => int 8
      'title' => string 'big day' (length=7)
      'start' => string '2016-05-04' (length=10)
  2 => 
    array (size=3)
      'id' => int 9
      'title' => string 'marriage day' (length=12)
      'start' => string '2016-05-19' (length=10)
  3 => 
    array (size=3)
      'id' => int 10
      'title' => string 'Karthiks  bday' (length=14)
      'start' => string '2016-06-11' (length=10)
  4 => 
    array (size=3)
      'id' => int 12
     'title' => string 'Election date announced' (length=23)
      'start' => string '2016-06-01' (length=10)

Now, I'd like to insert array('sample_key' => 'sample_value') after all the elements of each array.

How can I do it? This is I want the result to be like this:-

array (size=6)
  0 => 
    array (size=3)
       'id' => int 7
      'title' => string 'Pongal' (length=6)
       'start' => string '2016-05-16' (length=10)
       ‘color’ => ‘red’
  1 => 
    array (size=3)
      'id' => int 8
      'title' => string 'big day' (length=7)
      'start' => string '2016-05-04' (length=10)
      ‘color’ => ‘red’
  2 => 
    array (size=3)
      'id' => int 9
      'title' => string 'marriage day' (length=12)
      'start' => string '2016-05-19' (length=10)
      ‘color’ => ‘red’
  3 => 
    array (size=3)
      'id' => int 10
      'title' => string 'Karthiks  bday' (length=14)
      'start' => string '2016-06-11' (length=10)
      ‘color’ => ‘red’
  4 => 
    array (size=3)
      'id' => int 12
      'title' => string 'Election date announced' (length=23)
      'start' => string '2016-06-01' (length=10)
      ‘color’ => ‘red’

Note that I have added 'color' => 'red' to all the indexes

Answer

Murad Hasan picture Murad Hasan · May 20, 2016

Just do this: Working demo

using the & you can change the main array, and just use $val['color'] = 'red' to add a new key , value pair in the array.

foreach($arr as $key => &$val){
    $val['color'] = 'red';
}

Note that the 'write-back' feature of the ampersand persists even after the loop has finished: resetting $val to a new value will change the last element in $val, which is often unexpected. There are three ways around this class of bug:

  • Avoid write-back and just use the full array expression to write values inside the loop;
  • Don't re-use the $val variable in the same scope, even for another foreach() loop;
  • Use unset() on the $val variable to disconnect it from the array it will write back to.