TarikM TarikM - 15 days ago 9
Javascript Question

PHP merge two arrays like in javascript's push([[],[]])

I have two arrays which I want to combine in PHP:

Array1 = [123,456,789];

Array2 = [1,2,3];


I want to combine them as follows:

Array3 = [[123,1],[456,2],[789,3]];


In Javascript I can use the function push() in a forloop which looks like this:

Array3.push([array1[i],array2[i]]);


But I can't seem to figure out why this isn't possible with PHP? I have tried using

array_merge(array1,array2);
array3 = array1 + array2;


But neither works. Thanks in advance.

Answer

Are you looking for something like this? You might need to add null-checks if you want.

function array_combinemerge($arr1, $arr2) {
    $result = array();
    for ($i = 0; $i < count($arr1); $i++)
        $result[] = array($arr1[$i], $arr2[$i]);
    return $result;
}

Example code:

// example code
$Array1 = array(123,456,789);
$Array2 = array(1,2,3);
$Combined = array_combinemerge($Array1, $Array2);
print_r($Combined);

This gives you:

Array
(
    [0] => Array
        (
            [0] => 123
            [1] => 1
        )

    [1] => Array
        (
            [0] => 456
            [1] => 2
        )

    [2] => Array
        (
            [0] => 789
            [1] => 
        )

)