PHP array_merge

Created with Sketch.

PHP array_merge

Summary: in this tutorial, you will learn how to use the PHP array_merge() function to merge one or more arrays into one.

Introduction to the PHP array_merge() function

To merge one or more array into an array, you use the array_merge() function:

array_merge ( array ...$arrays ) : array

Code language: PHP (php)

The array_merge() function accepts one or more arrays and returns a new array that contains the elements from the input arrays.

The array_merge() function appends the elements of the next array to the last element of the previous one.

When the elements in the input arrays have the string keys, the later value for that key will overwrite the previous one.

However, if the array_merge() function will not overwrite the values with the same numeric keys. Instead, it renumbers the numeric keys starting from zero in the result array.

Starting from PHP 7.4.0, you can call the array_merge() function without any arguments. In this case, the function will return an empty array.

PHP array_merge() function examples

Let’s take some examples of using the array_merge() function.

1) Simple array_merge() function example

The following example uses the array_merge() function to merge two arrays into one:

<?php

$server_side = ['PHP'];

$client_side = ['JavaScript', 'CSS', 'HTML'];

$full_stack = array_merge($server_side, $client_side);

print_r($full_stack);

Code language: HTML, XML (xml)

Output:

Array
(
[0] => PHP
[1] => JavaScript
[2] => CSS
[3] => HTML
)

Code language: PHP (php)

How it works.

  • First, define two indexed arrays: $server_side and $client_side.
  • Second, merge the $server_side and $client_side arrays into one array using the array_merge() function.
  • Third, show the result array.

As you can see clearly from the output, the array_merge() function renumbers the numeric keys of the elements in the result array.

2) Using array_merge() function with string keys

The following example uses the array_merge() function with the array with the string keys:

<?php

$before = [
'PHP' => 2,
'JavaScript' => 4,
'HTML' => 4,
'CSS' => 3
];

$after = [
'PHP' => 5,
'JavaScript' => 5,
'MySQL' => 4,
];

$skills = array_merge($before, $after);

print_r($skills);

Code language: HTML, XML (xml)

Output:

Array
(
[PHP] => 5
[JavaScript] => 5
[HTML] => 4
[CSS] => 3
[MySQL] => 4
)

Code language: PHP (php)

Because both $before and $after arrays have the same elements with the same string keys PHP and JavaScript, the elements in the $before array overwrites the ones in the $after array.

Summary

  • Use the PHP array_merge() function to merge elements of two or more arrays into a single array.

Leave a Reply

Your email address will not be published. Required fields are marked *