Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Push Array values into another Array in PHP? [duplicate]

Tags:

arrays

php

I'm working with PHP 5.6 and I want to push values from an array in the end of another array so I tried the array_push function but It pushed the whole array like this:

Array
(
    [0] => Array
        (
            [0] => a
            [1] => b
            [2] => c
        )

    [1] => Array
       (
           [0] => d
           [1] => e
           [2] => f
       )
)

What I'm looking for is this :

 Array
 (
    [0] => Array
        (
            [0] => a
            [1] => b
            [2] => c
            [3] => d
            [4] => e
            [5] => f
       )

Is there any simpler way than looping over the array and adding values one by one :)

like image 927
storm Avatar asked Sep 11 '26 09:09

storm


2 Answers

$r = array
(
    array("a","b","c"),
    array("d","e","f")
);
$r1[] = call_user_func_array('array_merge', $r);
print_r($r1);
like image 172
u_mulder Avatar answered Sep 12 '26 23:09

u_mulder


You can use the array_merge function, which appends together multiple arrays:

<?php
$array1 = array('a','b','c');
$array2 = array('d','e','f');
$array1 = array_merge($array1, $array2);
var_dump($array1); // array('a', 'b', 'c', 'd', 'e', 'f')
like image 30
Nayeem Sarwar Avatar answered Sep 13 '26 01:09

Nayeem Sarwar



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!