Search code examples
multidimensional-arrayarray-push

How push into array without creating numbered indexes in a multidimensional array in PHP?


I want to use array_push() to add to an array, but it always adds a [0] => Array level. How can I prevent that, or take that out afterwards?

For example, I'm trying to push into the '[addOns] => Array' with this:

$addOnid='gcl1';
$addOnid_arr=array('inheritedFromId' => $addOnid);
array_push($result['addOns'], $addOnid_arr);

The array_push is resulting in this:

Array
(
    [addOns] => Array
        (
            [inheritedFromId] => gcl2
        )
        [0] => Array
            (
               [inheritedFromId] => gcl1
            )

)

And want to make it:

Array
(
    [addOns] => Array
        (
            [inheritedFromId] => gcl2
        )
        (
            [inheritedFromId] => gcl1
        )
)

...basically just getting rid of all the [0] => Array, moving all the subarrays up a level.

Maybe I haven't been using the right queries, but I haven't been able to find out how to do this.


Solution

  • Simple just use this instead:

    $addOnid = 'gcl1';
    $addOnid_arr['addOns'][] = ['inheritedFromId' => $addOnid];