How to add arrays to another array with php?

Member

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

How to add arrays to another array with php?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by elisha_langworth , 10 months ago

@brandy 

To add one or more arrays to another array in PHP, you can use the array_merge() function. Here's an example of how to add two arrays to another array:

1
2
3
4
5
6
$array1 = array('apple', 'banana', 'cherry');
$array2 = array('orange', 'pear', 'grape');

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

print_r($combinedArray);


This will output:

1
2
3
4
5
6
7
8
9
Array
(
    [0] => apple
    [1] => banana
    [2] => cherry
    [3] => orange
    [4] => pear
    [5] => grape
)


You can also add multiple arrays by passing them as additional arguments to the array_merge() function. For example:

1
$combinedArray = array_merge($array1, $array2, $array3);