The array_unshift()
function in PHP is used to add one or more elements to the beginning of an array. It shifts all existing elements to higher indices and inserts the new element(s) at the start of the array.
Syntax:
array_unshift(array &$array, mixed ...$values): int
- $array: The input array that will be modified (passed by reference).
- $values: The value(s) to be added at the beginning of the array. You can pass one or more values.
The function returns the new number of elements in the array after the values have been added.
Example 1: Adding a Single Element
$fruits = ["apple", "banana", "cherry"];
array_unshift($fruits, "orange");
print_r($fruits);
Output:
Array
(
[0] => orange
[1] => apple
[2] => banana
[3] => cherry
)
In this example, "orange" is added to the beginning of the $fruits
array.
Example 2: Adding Multiple Elements
$fruits = ["apple", "banana", "cherry"];
array_unshift($fruits, "grape", "pineapple");
print_r($fruits);
Output:
Array
(
[0] => grape
[1] => pineapple
[2] => apple
[3] => banana
[4] => cherry
)
Here, both "grape" and "pineapple" are added to the beginning of the $fruits
array.
Example 3: Array with Mixed Data Types
$details = [100, "John", true];
array_unshift($details, "Manager", 200);
print_r($details);
Output:
Array
(
[0] => Manager
[1] => 200
[2] => 100
[3] => John
[4] => 1
)
In this example, "Manager" and 200 are added at the beginning of the $details
array.
Example 4: Return Value (Number of Elements)
$fruits = ["apple", "banana"];
$length = array_unshift($fruits, "cherry", "orange");
echo "New length of the array: " . $length; // Output: New length of the array: 4
The function returns the number of elements in the array after modification, which is 4 in this case.
Key Points:
array_unshift()
modifies the original array (it is passed by reference).
- It can accept multiple values to insert at the beginning.
- The return value is the new number of elements in the array.