What is the array_unshift method in PHP?

The array_unshift method can be used to add one or more elements to the beginning of an array.

Syntax

array_unshift(array, value, ...)

Parameters

  • array: the array to add values to.
  • value: the value to be added.

Points to note

  • This method appends the elements in the order in which it is passed as an argument.

  • The numeric index of the elements is reassigned, starting from zero.

  • Non-numeric keys remain unchanged.

  • This method returns the new length of the array after it appends the passed elements.

Example

<?php
$numbers = [
1,
2,
'three' => 3,
4
];
printArray($numbers);
array_unshift($numbers, 0);
printArray($numbers);
array_unshift($numbers, -2, -1);
printArray($numbers);
// function to print the array
function printArray($array){
echo "The array is ";
print_r($array);
echo "\n";
}
?>

In the code above:

  • We created an array called numbers.

  • We created a printArray function to print the array.

  • We called the array_unshift method with single and multiple arguments to append elements to the beginning of the array.

Free Resources