PASSWORD RESET

Your destination for complete Tech news

PHP

How to remove the last item from an array in PHP?

529 0
< 1 min read

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')

Leave A Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.