How to insert array to array in php?

by jasen_gottlieb , in category: PHP General , 10 months ago

How to insert array to array in php?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by hal.littel , 10 months ago

@jasen_gottlieb 

To insert an array into another array in PHP, you can use the array_merge function. Here's an example:

1
2
3
4
5
6
$array1 = [1, 2, 3];
$array2 = [4, 5, 6];

$result = array_merge($array1, $array2);

print_r($result);


Output:

1
2
3
4
5
6
7
8
9
Array
(
    [0] => 1
    [1] => 2
    [2] => 3
    [3] => 4
    [4] => 5
    [5] => 6
)


In this example, the array_merge function is used to merge $array1 and $array2 into a new array called $result. The resulting array will contain all the elements from both arrays.


If you want to merge multiple arrays together, you can pass them as separate arguments to the array_merge function:

1
2
3
4
5
6
7
$array1 = [1, 2, 3];
$array2 = [4, 5, 6];
$array3 = [7, 8, 9];

$result = array_merge($array1, $array2, $array3);

print_r($result);


Output:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
Array
(
    [0] => 1
    [1] => 2
    [2] => 3
    [3] => 4
    [4] => 5
    [5] => 6
    [6] => 7
    [7] => 8
    [8] => 9
)


In this case, $result will contain all the elements from $array1, $array2, and $array3.