PHP provides two useful functions for working with the beginning of arrays: array_shift() and array_unshift(). These functions allow you to remove and add elements to the beginning of an array, respectively.
array_shift() removes the first element of an arrayarray_unshift() adds elements to the start of an arrayVisualize how the array changes and re-indexes.
// Removes and returns the first element of the array
array_shift($array);
// Adds one or more elements to the beginning of the array
array_unshift($array, $value1, $value2);
// Removing the first element from the array
<?php
$fruits = array("Apple", "Banana", "Cherry");
$removed = array_shift($fruits);
echo $removed;
print_r($fruits);
?>
The function removes Apple from the beginning of the array and returns it. The remaining array elements are reindexed automatically.
// Adding elements to the beginning of the array
<?php
$fruits = array("Banana", "Cherry");
array_unshift($fruits, "Apple", "Mango");
print_r($fruits);
?>
The new elements are inserted at the front of the array, and the total element count increases accordingly.
array_shift() if neededarray_shift()array_unshift()