Open In App

How to Remove Last Element from an Array in PHP ?

Last Updated : 17 Jan, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

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];
  
// Remove last element using 
// array_pop() function
$lastElement = array_pop($arr);
  
// Display the modified array and
// the removed element
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];
  
// Remove last element
$arr = array_slice($arr, 0, -1);
  
// Display the modified array
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];
  
// Remove the last element
unset($arr[count($arr) - 1]);
  
// Display the modified array
echo "Modified Array: ";
print_r($arr);
  
?>


Output

Modified Array: Array
(
    [0] => 1
    [1] => 2
    [2] => 3
    [3] => 4
)


Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads