remove the last element from an array in PHP.

Question

Answers ( 1 )

    0
    2024-01-11T18:05:21+00:00

    To remove the last element from an array in PHP, you can use the array_pop() function. This function shortens the array by one element and returns the value of the removed element. Here's an example:

    <?php
    $array = [1, 2, 3, 4, 5];
    
    // Remove the last element
    $removedElement = array_pop($array);
    
    // The array is now [1, 2, 3, 4]
    // $removedElement is 5
    ?>
    

    This is the most straightforward and commonly used method to remove the last element from an array in PHP. It's important to note that array_pop() modifies the original array and also works on arrays that are numerically indexed. If the array is empty (or not an array), NULL will be returned and a warning will be issued.

Leave an answer