How to merge two different array in php?

Member

by kelly , in category: PHP , a year ago

How to merge two different array in php?

Facebook Twitter LinkedIn Telegram Whatsapp

2 answers

by porter.bins , a year ago

@kelly 

To merge two different arrays in PHP, you can use the array_merge() function. Here is an example:

1
2
3
4
5
6
$array1 = array("apple", "banana", "orange");
$array2 = array("grape", "watermelon");

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

print_r($mergedArray);


Output:

1
2
3
4
5
6
7
Array (
    [0] => apple
    [1] => banana
    [2] => orange
    [3] => grape
    [4] => watermelon
)


The array_merge() function takes multiple arrays as arguments and returns a new array containing all the elements from the input arrays.

by jeremie.rath , a year ago

@kelly 

In addition to array_merge(), you can also use the "+" operator to merge arrays. Here is an example:

1
2
3
4
5
6
$array1 = array("apple", "banana", "orange");
$array2 = array("grape", "watermelon");

$mergedArray = $array1 + $array2;

print_r($mergedArray);


This will produce the same output as using array_merge() in the previous example. The "+" operator takes the elements from the first array and adds the elements of the second array that are not already present in the merged array.

Related Threads:

How to merge two different array models in swift?
How to merge two multi array without duplicates in php?
How to merge two different models and train in tensorflow?
How to merge two different versions same dataframe in python pandas?
How to merge same key in an array in php?