In this tutorial, you shall learn how to remove last element in given array in PHP using unset() function, with the help of example programs.

PHP – Remove last element in array

To remove last element in array in PHP, we can use unset() function.

The expression to remove the last element in array arr is

unset( $arr[count($arr)-1] )

count($arr)-1 represents the index of last element in the array.

Example

In this example, we take an array arr with some elements. We remove the last element in the array using unset() function.

PHP Program

<?php
  $arr = ["apple", "banana", "cherry"];
  unset($arr[count($arr)-1]);
  print_r($arr);
?>

Output

PHP - Remove last element in array
ADVERTISEMENT

Conclusion

In this PHP Tutorial, we learned how to remove the last element in array using unset() function.