What is the usage of array_unshift in PHP?
The array_unshift function is used to insert one or more elements at the beginning of an array. It inserts the given elements at the start of the array and reestablishes the indexing relationship.
The function syntax is as follows: array_unshift(array $array, mixed $value1, mixed $value2, …): int
Explanation of parameters:
- Array: required, the array to be operated on.
- $value1, $value2…: Optional values to be inserted at the beginning of the array.
Return value: The new length of the array after the insertion of the element.
“Do you have any plans for the weekend?”
– Do you have any plans for this weekend?
$stack = array("orange", "banana");
array_unshift($stack, "apple", "raspberry");
print_r($stack);
output:
Array
(
[0] => apple
[1] => raspberry
[2] => orange
[3] => banana
)
In the example above, the original array is [“orange”, “banana”], and using array_unshift, two elements “apple” and “raspberry” were inserted, resulting in the final array becoming [“apple”, “raspberry”, “orange”, “banana”].