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
$arr1 = array (
"GeeksforGeeks" ,
"Computer" ,
"Science" ,
"Portal"
);
$arr2 = array (
"Welcome"
);
$mergeArr = array_merge ( $arr1 , $arr2 );
print_r( $mergeArr );
?>
|
Output:
Array
(
[0] => GeeksforGeeks
[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
$array = array (
"GeeksforGeeks" ,
"Computer" ,
"Science" ,
"Portal"
);
$element = "Welcome" ;
array_unshift ( $array , $element );
print_r( $array );
?>
|
Output:
Array
(
[0] => Welcome
[1] => GeeksforGeeks
[2] => Computer
[3] => Science
[4] => Portal
)
Example 2:
php
<?php
$array = array (
"p" => "GeeksforGeeks" ,
"q" => "Computer" ,
"r" => "Science" ,
"s" => "Portal"
);
$element = "Welcome" ;
array_unshift ( $array , $element );
print_r( $array );
?>
|
Output:
Array
(
[0] => Welcome
[p] => GeeksforGeeks
[q] => Computer
[r] => Science
[s] => Portal
)
Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape,
GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out -
check it out now!
Last Updated :
27 Apr, 2023
Like Article
Save Article