PHP Remove Last Element from Array
Syntax
array_pop(array $array): mixed
Example
$fruits = ['apple', 'banana', 'orange'];
$lastFruit = array_pop($fruits);
print_r($fruits);
echo $lastFruit;
Output
Array
(
[0] => apple
[1] => banana
)
orange
Explanation
The array_pop()
function removes and returns the last element of the given array. It also shortens the array by one element.
In the above example, we have an array of fruits. We use array_pop()
function to remove the last element 'orange' from the array and store it in a variable $lastFruit. We then print the modified array using print_r()
and the removed last element using echo
.
Use
The array_pop()
function can be used when we want to remove the last element of an array without knowing its index. It returns the removed element which can be stored in a variable for further use.
Important Points
- The
array_pop()
function only removes the last element of the array. - If the array is empty, the function returns NULL.
- It modifies the original array and shortens it by one element.
Summary
- The
array_pop()
function removes and returns the last element of the given array. - It shortens the array by one element.
- It can be used when we want to remove the last element of an array without knowing its index.