How to Remove Last Element from an Array in PHP ?
Last Updated :
17 Jan, 2024
Removing the last element from an array is a common operation in PHP. There are several approaches to achieve this. In this article, we will explore different methods to remove the last element from an array.
Using array_pop() Function
The array_pop()
function is specifically designed to remove the last element from an array and return its value.
PHP
<?php
$arr = [1, 2, 3, 4, 5];
$lastElement = array_pop ( $arr );
echo "Modified Array: " ;
print_r( $arr );
echo "Removed Element: $lastElement" ;
?>
|
Output
Modified Array: Array
(
[0] => 1
[1] => 2
[2] => 3
[3] => 4
)
Removed Element: 5
Using array_slice() Function
Another approach is to use array_slice() function
to create a new array without the last element.
PHP
<?php
$arr = [1, 2, 3, 4, 5];
$arr = array_slice ( $arr , 0, -1);
echo "Modified Array: " ;
print_r( $arr );
?>
|
Output
Modified Array: Array
(
[0] => 1
[1] => 2
[2] => 3
[3] => 4
)
Using unset() Function
The unset() function can also be used to remove the last element, but it works by unsetting the array element at a specific index.
PHP
<?php
$arr = [1, 2, 3, 4, 5];
unset( $arr [ count ( $arr ) - 1]);
echo "Modified Array: " ;
print_r( $arr );
?>
|
Output
Modified Array: Array
(
[0] => 1
[1] => 2
[2] => 3
[3] => 4
)
Share your thoughts in the comments
Please Login to comment...