The php array_shift() function allows us to get and delete the first element of an array in php.
$array = array(1, 2, 3, 4, 5);
array_shift($array);
print_r($array);
// Output:
Array
(
[0] => 2
[1] => 3
[2] => 4
[3] => 5
)
When working with arrays and collections of data in php, it is useful to be able to add or remove items from our data structures easily.
The array_shift() function gives us the ability to remove the first element of a given array.
To use array_shift(), just pass an array.
Below is an example of how you can use array_shift() to delete the first element of an array in php.
$array = array(1, 2, 3, 4, 5);
array_shift($array);
print_r($array);
// Output:
Array
(
[0] => 2
[1] => 3
[2] => 4
[3] => 5
)
Getting the First Element of an Array with array_shift()
The array_shift() function returns the first element of an array. So with array_shift(), we can get the first element of an array.
Below is a simple example in php of how to get the first element of an array using array_shift().
$array = array(1, 2, 3, 4, 5);
echo array_shift($array);
// Output:
1
Getting the Last Element of an Array with array_pop()
If you’d instead like to get the last element of an array, you can use the php array_pop() function.
The array_pop() function does the opposite of array_shift() – it gets the last element and deletes it from the array.
Below is an example of how you can use array_pop() to delete the last element of an array in php.
$array = array(1, 2, 3, 4, 5);
array_pop($array);
print_r($array);
// Output:
Array
(
[0] => 1
[1] => 2
[2] => 3
[3] => 4
)
Hopefully this article has been useful for you to learn how to use the php array_shift() function.