The php array_pop() function allows us to get and 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
)
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_pop() function gives us the ability to get and remove the last element of a given array.
To use array_pop(), just pass an 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
)
Getting the Last Element of an Array with array_pop()
The array_pop() function returns the last element of an array. So with array_pop(), we can get the last element of an array.
Below is a simple example in php of how to get the last element of an array using array_pop().
$array = array(1, 2, 3, 4, 5);
echo array_pop($array);
// Output:
5
Removing the First Element from an Array with array_shift() in php
If you’d instead like to get the first element of an array, you can use the php array_shift() function.
The array_shift() function does the opposite of array_pop() – it gets the firstelement and deletes it from the 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
)
Hopefully this article has been useful for you to learn how to use the php array_pop() function.