How to use array_unshift() function In PHP
The array_unshift() function is used to add one or more elements at the beginning of the array.
Example 1:
<?php
// Declare an array
$array = array(
"w3wiki",
"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] => w3wiki [2] => Computer [3] => Science [4] => Portal )
Example 2:
<?php
// Declare an associative array
$array = array(
"p" => "w3wiki",
"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] => w3wiki [q] => Computer [r] => Science [s] => Portal )
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:
Contact Us