In PHP, arrays are a very common data type, and PHP provides many built-in functions to manipulate arrays. Today, we will introduce a very useful function — `array_merge()`, which can merge multiple arrays into one and return the merged result. In this article, we will explore the usage of the `array_merge()` function and provide some examples.
The syntax of the `array_merge()` function is very simple:
array_merge ( array $array1 [, array $... ] ) : array
This function accepts multiple arrays as parameters and returns a new array containing all the merged elements.
Here is an example of merging two arrays:
$array1 = array('apple', 'banana', 'orange');
$array2 = array('kiwi', 'melon', 'grape');
$result = array_merge($array1, $array2);
print_r($result);
Output:
Array
(
[0] => apple
[1] => banana
[2] => orange
[3] => kiwi
[4] => melon
[5] => grape
)
In this example, we have two arrays, `$array1` and `$array2`. By calling the `array_merge()` function, these two arrays are merged into a new array `$result`, which contains all the elements from the original arrays.
Here is an example of merging multiple arrays:
$array1 = array('apple', 'banana', 'orange');
$array2 = array('kiwi', 'melon', 'grape');
$array3 = array('strawberry', 'pineapple');
$result = array_merge($array1, $array2, $array3);
print_r($result);
Output:
Array
(
[0] => apple
[1] => banana
[2] => orange
[3] => kiwi
[4] => melon
[5] => grape
[6] => strawberry
[7] => pineapple
)
In this example, we have three arrays: `$array1`, `$array2`, and `$array3`. After calling the `array_merge()` function, these three arrays are merged into a new array `$result`, which contains all the elements from the original arrays.
The `array_merge()` function is not limited to regular arrays, it also works with associative arrays. Here’s an example of merging associative arrays:
$array1 = array('name' => 'John', 'age' => 25);
$array2 = array('name' => 'Jane', 'email' => 'jane@example.com');
$result = array_merge($array1, $array2);
print_r($result);
Output:
Array
(
[name] => Jane
[age] => 25
[email] => jane@example.com
)
In this example, both `$array1` and `$array2` are associative arrays. It’s important to note that both arrays have the same key `'name'`. When calling `array_merge()`, the value of the last key will overwrite the earlier one, so in the resulting `$result` array, the value of `'name'` will be `'Jane`.
The `array_merge()` function is a very useful tool in PHP for array manipulation. It works with both regular arrays and associative arrays, and it allows you to merge multiple arrays efficiently. In real-world development, `array_merge()` helps us handle array data more flexibly and conveniently.