To remove the last item from an array in PHP, you can use the array_pop()
function. This function removes the last element from an array, and returns the value of the removed element.
For example:
$fruits = array('apple', 'banana', 'cherry');
$last = array_pop($fruits);
// $last will be equal to 'cherry'
// $fruits will be equal to array('apple', 'banana')
You can also use the unset()
function to remove an element from an array by its key. For example:
$fruits = array('apple', 'banana', 'cherry');
unset($fruits[2]);
// $fruits will be equal to array(0 => 'apple', 1 => 'banana')
Note that using unset()
will renumber the keys of the array, starting from 0. If you want to preserve the keys, you can use the array_slice()
function to remove the last element of the array and return a new array with the remaining elements.
For example:
$fruits = array('a' => 'apple', 'b' => 'banana', 'c' => 'cherry');
$fruits = array_slice($fruits, 0, -1);
// $fruits will be equal to array('a' => 'apple', 'b' => 'banana')