How to use array_slice() Function In PHP

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
)

How to Remove Last Element from an Array in PHP ?

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.

Table of Content

  • Using array_pop() Function
  • Using array_slice() Function
  • Using unset() Function

Similar Reads

Using array_pop() Function

The array_pop() function is specifically designed to remove the last element from an array and return its value....

Using array_slice() Function

...

Using unset() Function

Another approach is to use array_slice() function to create a new array without the last element....

Contact Us