1

I tried to find a simple answer of following question, but failed.

I have a 2D array and an 1D array:

$arr_2D = array(
    array("product" => "apple", "quantity" => 2),
    array("product" => "Orange", "quantity" => 4),
    array("product" => "Banana", "quantity" => 5),
    array("product" => "Mango", "quantity" => 7)
);

$element = array("product" => "Lemon", "quantity" => 9);

I wish to push 1D array into 2D array, and get a new and big 2D array:

$arr_2D = array(
    array("product" => "apple", "quantity" => 2),
    array("product" => "Orange", "quantity" => 4),
    array("product" => "Banana", "quantity" => 5),
    array("product" => "Mango", "quantity" => 7),
    array("product" => "Lemon", "quantity" => 9)
);

I tried:

$arr_2D = array_push($arr_2D, $element);

but it does not work; it returns 5.

How can I use array_push()?

0

1 Answer 1

2

Is this what you want ? both array_push() and the shorthand [] notation will add the $element array to the end of the $arr_2D array :

$arr_2D = array(
    array("product" => "apple", "quantity" => 2),
    array("product" => "Orange", "quantity" => 4),
    array("product" => "Banana", "quantity" => 5),
    array("product" => "Mango", "quantity" => 7)
);

$element = array("product" => "Lemon", "quantity" => 9);

//using array_push()
array_push($arr_2D, $element);

//using shorthand notation
$arr_2D[] = $element;

//printing the updated 2D array
print_r($arr_2D);

output :

Array
(
    [0] => Array
        (
            [product] => apple
            [quantity] => 2
        )

    [1] => Array
        (
            [product] => Orange
            [quantity] => 4
        )

    [2] => Array
        (
            [product] => Banana
            [quantity] => 5
        )

    [3] => Array
        (
            [product] => Mango
            [quantity] => 7
        )

    [4] => Array
        (
            [product] => Lemon
            [quantity] => 9
        )
)
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.