There are two ways to insert an element at the beginning of an array, which are discussed below:
Using the function array_merge() :The array_merge() function is used to combine two or more arrays into one array. This function is used to combine the elements or values of two or more arrays into one array.
- Create an array containing the elements of the array.
- Create another array containing one element you want insert at the beginning of another array.
- Use the array_merge() function to concatenate both arrays and create one array.
Example:
// Declare the array
$arr1
=
array
(
" GeeksforGeeks "
,
"Computer"
,
" Science "
,
"Portal"
);
// Declare another array
// element to insert into
// start $arr1
$arr2
=
array
(
"Welcome"
);
// Custom array_merge() function for
// merge both arrays
$mergeArr
=
array_merge
(
$arr1
,
$arr2
);
print_r (
$mergeArr
);
?>
Exit:Array ([ 0] = > GeeksforGeeks [1] = > Computer [2] = > Science [3] = > Portal [4] = > Welcome)
Using the array_unshift() : function array_unshift() is used to add or more elements at the beginning of an array.Example 1:
// Declare the array
$array
=
array
(
" GeeksforGeeks "
,
"Computer"
,
"Science"
,
"Portal"
);
// Declare the variable containing the element
$element
=
"Welcome"
;
// Custom array_unshift() function for
// insert the element at the beginning of the array
array_unshift
(
$array
,
$element
);
print_r (
$array
);
?>
Exit:Array ([ 0] = > Welcome [1] = > GeeksforGeeks [2] = > Computer [3] = > Science [4] = > Portal)
Example 2:
// Declare an associative array
$array
=
array
(
"p"
= >
"GeeksforGeeks"
,
" q "
= >
"Computer"
,
" r "
= >
"Science"
,
"s"
= >
"Portal"
);
// Declare the variable containing the element
$element
=
"Welcome"
;
// Custom array_unshift() function for
// insert the element at the beginning of the array
array_unshift
(
$array
,
$element
);
print_r (
$array
);
?>
Exit:Array ([ 0] = > Welcome [p] = > GeeksforGeeks [q] = > Computer [r] = > Science [s] = > Portal)