PHP is a powerful server-side scripting language widely used for developing dynamic websites and applications. When working with arrays, you might sometimes need to add elements to the beginning of an array. For this, the array_unshift() function is a handy tool.
The array_unshift() function adds one or more elements to the beginning of an array and returns the new number of elements in the array. The syntax is as follows:
array_unshift(array $array, mixed $value1 [, mixed $value2, ...])
$array: The target array
$value1, $value2...: The values to be inserted (can be one or more)
Here's a simple example showing how to insert an element at the start of an array using array_unshift():
<?php
$fruits = array("apple", "orange", "banana");
echo "Before array_unshift:\n";
print_r($fruits);
array_unshift($fruits, "grape");
echo "After array_unshift:\n";
print_r($fruits);
?>
Expected output:
Before array_unshift:
Array
(
[0] => apple
[1] => orange
[2] => banana
)
After array_unshift:
Array
(
[0] => grape
[1] => apple
[2] => orange
[3] => banana
)
As shown, "grape" is successfully added at the beginning of the array.
The array_unshift() function also allows inserting multiple elements at once. Here's another example:
<?php
$numbers = array(3, 4, 5);
echo "Before array_unshift:\n";
print_r($numbers);
array_unshift($numbers, 1, 2);
echo "After array_unshift:\n";
print_r($numbers);
?>
Expected output:
Before array_unshift:
Array
(
[0] => 3
[1] => 4
[2] => 5
)
After array_unshift:
Array
(
[0] => 1
[1] => 2
[2] => 3
[3] => 4
[4] => 5
)
With this approach, you can easily add multiple values to the beginning of an array in one function call.
The array_unshift() function is a convenient and efficient way to insert elements at the start of an array in PHP. Whether you're adding one value or many, it eliminates the need to manually rebuild arrays. In real-world development, mastering such built-in functions can significantly streamline your code and improve maintainability.