remove an element from the end of an array in php

To remove the last element of an array in PHP, you can use the array_pop() function. Here's an example:

main.php
$myArray = ['apple', 'banana', 'cherry'];
$lastElement = array_pop($myArray);
print_r($myArray); // Output: Array ( [0] => apple [1] => banana )
echo $lastElement; // Output: cherry
182 chars
5 lines

Alternatively, you can use the end() function to get the last element of the array and then use array_slice() to remove it. Here's an example:

main.php
$myArray = ['apple', 'banana', 'cherry'];
$lastElement = end($myArray);
$myArray = array_slice($myArray, 0, -1);
print_r($myArray); // Output: Array ( [0] => apple [1] => banana )
echo $lastElement; // Output: cherry
217 chars
6 lines

Both methods achieve the same result, but array_pop() is slightly more concise.

related categories

gistlibby LogSnag