The array_unshift()
function adds a value onto the start of the array.
This is the opposite of the array_shift()
function.
PHP array_unshift() Function has the following syntax.
int array_unshift ( array &arr, mixed var [, mixed ...] )
Parameter | Is Required | Description |
---|---|---|
array | Required. | Array to be added |
value1 | Required. | Value to insert |
value2 | Optional. | Value to insert |
value3 | Optional. | Value to insert |
You can't add key/value pairs to associative arrays using array_unshift() or its counterpart, array_pop(). However, you can work around this by using array_merge().
With array_unshift() and array_push(), if you include an array as one of the values to add, the array is added to the original array as an element, turning the original array into a multidimensional array:
<?PHP
$authors = array( "Java", "PHP", "CSS", "HTML" );
$newAuthors = array( "Javascript", "Python" );
echo array_push( $authors, $newAuthors ) . "\n";
print_r( $authors );
?>
If you instead want to add the elements of the array individually to the original array, use array_merge().
The code above generates the following result.
Adds a value onto the start of the array
<?PHP
$firstname = "java2s.com";
$names = array("A", "B", "C", "D", "E");
array_unshift($names, $firstname);
print_r($names);
?>
The code above generates the following result.
Adds two value onto the start of the array
<?PHP
$authors = array( "Java", "PHP", "CSS", "HTML" );
echo array_unshift( $authors, "Javascript", "Python" ) . "\n"; // Displays "6"
print_r( $authors );
?>
The code above generates the following result.