How to remove last element from an array in PHP?
Answer: Using array_pop()
function
We can remove the last element from an array using the array_pop()
function. This function takes an array as its input and returns the last array element, which is being removed. It returns NULL if the array is empty.
After removing the last element from the array then the array index is modified, and the length of the array is reduced by one. The length of the array is reduced only when the keys of the array are numerical.
Example: Removing last array element
In the given example, we have removed the last array element from the given array named $arr
using the array_pop()
function.
<!DOCTYPE html>
<html>
<head>
<title>Removing last element of an array</title>
</head>
<body>
<?php
$arr = array("C++", "C", "JavaScript", "jQuery", "PHP");
$deletedVal = array_pop($arr);
print_r($deletedVal);
?>
</body>
</html>
PHP
Using array_slice()
function
The array_slice()
function is used to slice the array element. We can also remove the last element of an array using the array_slice()
function. This function takes the given array as its input and returns the selected part of an array.
Example: Removing the last element of an array
In the given example, we have removed the last element of the given array named $arr
using the array_slice()
function.
<!DOCTYPE html>
<html>
<head>
<title>Removing last element of an array</title>
</head>
<body>
<?php
$arr = array("C++", "C", "JavaScript", "jQuery", "PHP");
$removedVal = array_slice($arr, 0, -1);
print_r($removedVal);
?>
</body>
</html>
Array ( [0] => C++ [1] => C [2] => JavaScript [3] => jQuery )
Conclusion
In this lesson, we have learned how to remove the last element of an array in PHP. Here, we have discussed two methods to remove the last element from the given array. At first, we used the array_pop()
function, which is a predefined PHP function used to remove the last element from an array. Then we have used the array_slice()
function, this function is used to slice the array element, and then it returns the element.