In PHP development, arrays are one of the most commonly used data structures. When we need to insert a new element at the beginning of an array, we can use the PHP array_unshift() function. This article will introduce how to use the array_unshift() function, helping you understand and apply this functionality more effectively.
The array_unshift() function is used to insert one or more elements at the beginning of an array, and it changes the length of the array. After insertion, the existing elements will be shifted to the right.
array_unshift(array &$array, mixed $value1 [, mixed $... ])
Below is a simple example that demonstrates how to use array_unshift() to insert an element at the beginning of an array:
<?php $fruit = array("apple", "banana", "orange"); echo "Original Array:"; print_r($fruit); array_unshift($fruit, "lemon"); echo "New Array After Insertion:"; print_r($fruit); ?>
In the example above, we first created an array $fruit containing three fruit elements. Then, we used the array_unshift() function to insert the element "lemon" at the beginning of the array, and printed the result using the print_r() function.
Running the code will produce the following output:
Original Array:
(
[0] => apple [1] => banana [2] => orange
)
New Array After Insertion:
(
[0] => lemon [1] => apple [2] => banana [3] => orange
)
From the output, we can see that the array_unshift() function successfully inserted "lemon" at the beginning of the array, and the existing elements were shifted to the right.
It’s important to note that the array_unshift() function returns the new length of the array after the elements are inserted, not the modified array itself.
In addition to inserting a single element, the array_unshift() function can also be used to insert multiple elements at once. Here’s another example:
<?php $numbers = array(4, 5); echo "Original Array:"; print_r($numbers); array_unshift($numbers, 1, 2, 3); echo "New Array After Insertion:"; print_r($numbers); ?>
Running the above code will produce the following output:
Original Array:
(
[0] => 4 [1] => 5
)
New Array After Insertion:
(
[0] => 1 [1] => 2 [2] => 3 [3] => 4 [4] => 5
)
From this example, we can see that the array_unshift() function can insert multiple elements at once at the beginning of the array, and the array length is adjusted accordingly.
The array_unshift() function is one of the commonly used array functions in PHP. It makes it easy to insert one or more elements at the beginning of an array. Once you master this function, you will be able to handle array manipulations more effectively in your development work.