How insert multiple array item into one array in php?

by herminia_bruen , in category: PHP General , a year ago

How insert multiple array item into one array in php?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by giovanny.lueilwitz , a year ago

@herminia_bruen 

To insert multiple array items into one array in PHP, you can use the array_merge() function. This function merges two or more arrays into a single array. Here's how you can use it to insert multiple array items into one array:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
// Arrays to be inserted
$array1 = ['item1', 'item2'];
$array2 = ['item3', 'item4'];

// Array to be updated
$mainArray = ['existing1', 'existing2'];

// Merge all arrays into one
$mergedArray = array_merge($mainArray, $array1, $array2);

// Output the merged array
print_r($mergedArray);


Output:

1
2
3
4
5
6
7
8
9
Array
(
    [0] => existing1
    [1] => existing2
    [2] => item1
    [3] => item2
    [4] => item3
    [5] => item4
)


In the above example, the array_merge() function is used to merge $mainArray, $array1, and $array2 into $mergedArray. The resulting array contains all the elements from the individual arrays in the order they were specified.