Friday, October 24, 2025
HomeLanguagesHow to insert an item at the beginning of an array in...

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:

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. 

  • Create an array containing array elements.
  • Create another array containing one element which needs to insert 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(
    "neveropen",
    "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] => neveropen
    [1] => Computer
    [2] => Science
    [3] => Portal
    [4] => Welcome
)

 

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

Example 1: 

php




<?php
 
// Declare an array
$array = array(
    "neveropen",
    "Computer",
    "Science",
    "Portal"
);
 
// Declare a variable containing element
$element = "Welcome";
 
// User array_unshift() function to
// insert element at beginning of array
array_unshift( $array, $element );
 
print_r($array);
 
?>


Output: 

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

 

Example 2: 

php




<?php
 
// Declare an associative array
$array = array(
    "p" => "neveropen",
    "q" => "Computer",
    "r" => "Science",
    "s" => "Portal"
);
 
// Declare a variable containing element
$element = "Welcome";
 
// User array_unshift() function to
// insert element at beginning of array
array_unshift( $array, $element );
 
print_r($array);
 
?>


Output: 

Array
(
    [0] => Welcome
    [p] => neveropen
    [q] => Computer
    [r] => Science
    [s] => Portal
)

 

RELATED ARTICLES

Most Popular

Dominic
32361 POSTS0 COMMENTS
Milvus
88 POSTS0 COMMENTS
Nango Kala
6728 POSTS0 COMMENTS
Nicole Veronica
11892 POSTS0 COMMENTS
Nokonwaba Nkukhwana
11954 POSTS0 COMMENTS
Shaida Kate Naidoo
6852 POSTS0 COMMENTS
Ted Musemwa
7113 POSTS0 COMMENTS
Thapelo Manthata
6805 POSTS0 COMMENTS
Umr Jansen
6801 POSTS0 COMMENTS