How to use array_merge() Function In PHP

The array_merge() function is used to merge two or more arrays into a single array. This function is used to merge the elements or values of two or more arrays together into a single array. 

  • Create an array containing array elements.
  • Create another array containing one element that needs to be inserted at the beginning of another array.
  • Use the array_merge() function to merge both arrays to create a single array.

Example: 

php
<?php

// Declare an array
$arr1 = array(
    "w3wiki",
    "Computer",
    "Science",
    "Portal"
);

// Declare another array containing
// element which need to insert at
// the beginning of $arr1
$arr2 = array(
    "Welcome"
);

// User array_merge() function to
// merge both array
$mergeArr = array_merge( $arr1, $arr2 );

print_r($mergeArr);

?>

Output
Array
(
    [0] => w3wiki
    [1] => Computer
    [2] => Science
    [3] => Portal
    [4] => Welcome
)

How to insert an item at the beginning of an array in PHP ?

Arrays in PHP are a type of data structure that allows us to store multiple elements of similar data type under a single variable thereby saving us the effort of creating a different variable for every data. The arrays are helpful to create a list of elements of similar types, which can be accessed using their index or key. 

There are two methods to insert an item at the beginning of an array which is discussed below:

Similar Reads

Using array_merge() Function

The array_merge() function is used to merge two or more arrays into a single array. This function is used to merge the elements or values of two or more arrays together into a single array....

Using array_unshift() function

The array_unshift() function is used to add one or more elements at the beginning of the array....

Using array_splice()

Using array_splice() to insert an item at the beginning of an array works by specifying the position (0) where the new element should be inserted, setting the length to 0 (no elements removed), and adding the new element, thus modifying the original array in place....

Contact Us