PHP is a popular server-side programming language that is widely used in web development and data processing. Like other programming languages, PHP also provides many built-in functions to simplify the work of developers. One of the commonly used functions is array_unshift()
.
array_unshift()
The function is to add elements to the beginning of the array. It can be used in many scenarios, for example:
Add an element at the beginning of the array
$fruits = array('orange', 'apple', 'banana'); array_unshift($fruits, 'cherry'); print_r($fruits);
The output of the above code will be:
Array ( [0] => cherry [1] => orange [2] => apple [3] => banana )
Such as As you can see, array_unshift()
adds the new element cherry
to the beginning of the array.
Add multiple elements to the beginning of the array
$names = array('Alice', 'Bob'); array_unshift($names, 'Charlie', 'David'); print_r($names);
The output of the above code is:
Array ( [0] => Charlie [1] => David [2] => Alice [3] => Bob )
As you can see, in this case , we can add multiple elements to the array at once.
Use one array to add elements to the beginning of another array
$numbers = array(1, 2, 3); $more_numbers = array(4, 5, 6); array_unshift($numbers, ...$more_numbers); print_r($numbers);
The output of the above code is:
Array ( [0] => 4 [1] => 5 [2] => 6 [3] => 1 [4] => 2 [5] => 3 )
Here, we use PHP The ...
operators introduced in 7.4 expand the elements in the second array and add them to the beginning of the first array all at once.
Add elements to an empty array
$empty_array = array(); array_unshift($empty_array, 'hello'); print_r($empty_array);
This example demonstrates how to use the array_unshift()
function on an empty array.
In these application scenarios, the array_unshift()
function can come in handy. It helps us add elements to the beginning of the array easily. In addition, it should be noted that this function modifies the array in place, which means that it directly modifies the original array and does not return any value.
The array_unshift()
function is also a very useful tool when we need to indent or sort an existing array. If you are used to using the array_push()
function to add elements to the end of the array, then now you have learned a new trick to add elements to the beginning of the array through array_unshift()
element.
The above is the detailed content of Array functions in PHP8: various application scenarios of array_unshift(). For more information, please follow other related articles on the PHP Chinese website!