Skip to main content

How to Remove the Last Element from an Array in PHP

The PHP array_pop() function is a built-in function that can be used to remove an element or value from the end of an array. The function also returns the last value of the array. However, if the array is empty (or the variable is not an array), the returned value will be NULL.

This function is typically used when you need to remove an element from an array but don’t want to destroy the entire array. For instance, if you have an array of strings and want to remove the last string, you would use array_pop(). The function is also useful for removing items from a stack, as it removes the topmost item. To use this function, simply pass the name of the array as a parameter.

The function will then remove the last element from the array and return it. If you need to remove multiple elements from an array, you can use the array_splice() function.

$languages = ["Go", "Dart", "Kotlin", "Swift"];
 
$deletedlanguages  = array_pop($languages);
var_dump($languages);
var_dump($deletedlanguages);
//output
array(3) {
  [0]=>
  string(2) "Go"
  [1]=>
  string(4) "Dart"
  [2]=>
  string(6) "Kotlin"
}
string(5) "Swift"

By continuing to use the site, you agree to the use of cookies.