1

I'm trying to add additional entry to an existing multidimensional array using array_push()

Here is my array: $array =

Array
(
    [0] => Array
        (
            [label] => Black
            [quantity] => 10
        )

    [1] => Array
        (
            [label] => Yellow
            [quantity] => 20
        )

    [2] => Array
        (
            [label] => Red
            [quantity] => 30
        )
)

What I need now is to add price key after each [quantity], so the final result is:

Array
(
    [0] => Array
        (
            [label] => Black
            [quantity] => 10
            [price] => 0
        )

    [1] => Array
        (
            [label] => Yellow
            [quantity] => 20
            [price] => 0
        )

    [2] => Array
        (
            [label] => Red
            [quantity] => 30
            [price] => 0
        )
)

$price['price'][] = 0; I have tried using array_push($price['price'], $array)

but that doesn't work, it just returns number 2.

2 Answers 2

2

You have an array of arrays. You need to iterate over it to add the price to each sub-array.

foreach($array as $key => $value) {
  $array[$key]['price'] = 0;
}

I don't think you want to use array_push() in this situation.

Sign up to request clarification or add additional context in comments.

Comments

0
foreach ($price as $priceItem) {
$priceItem['price']=0;
$newPrice[]= $priceItem;
}
var_dump($newPrice);

1 Comment

With this way, You have 2 arrays. Not overraid the first one.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.