Search code examples
phparraysarray-mergearray-push

Push or Merge data into existing Array


When working with existing code, it takes one array and places it into another in the fashion shown below.

I believe the empty brackets are the same thing as simply pushing it and appending it to the first available index.

$g['DATA'][] = $p;

After this is done, I have my own array that I would like to append to this as well. I tried using array_merge() with $g['DATA'][]as a parameter, but this is invalid for obvious reasons.

My only thought is to create a foreach loop counter so I can figure out the actual index it created, however I have to assume there is some cleaner way to do this?


Solution

  • Just simply use the count() of your $g["DATA"] array as index and then you can merge it like this:

    $g['DATA'][count($g["DATA"])-1] = array_merge($g['DATA'][count($g["DATA"])-1], $ownArray);
             //^^^^^^^^^^^^^^^^^^^                           ^^^^^^^^^^^^^^^^^^^
             // -1 Because an array is based index 0 -> means count() - 1 = last key