Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How do I use PHP function array_push() in 2 Dimensional array?

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

$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);

and not work.

How and Can I use function array_push?

>Solution :

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
        )
)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading