PHP array_pop() Function: How To Remove Last Element From Array

In this tutorial, we will learn how to use the pop() function in PHP to delete the last element in a given array.

PHP array_pop() Function: How To Remove Last Element From Array

Array operations refer to the various manipulations that can be performed on arrays, such as accessing, modifying, adding, removing, sorting, and searching elements. Arrays are a fundamental data structure in computer programming and are used extensively in algorithms, data structures, and applications.

PHP pop() Function

The following depicts the syntax for the pop() function in PHP.

array_pop(array &$array): mixed

The function accepts only one parameter:

  1. array - the target array whose last element you wish to delete.

The function removes the last element in the array and return it to the caller.

NOTE: The function will reset() the array pointer of the input array after use.

Examples

Example pop() function usage.

// Create an array
$fruits = array("apple", "banana", "orange", "grape");

// Remove the last element from the array
$last_fruit = array_pop($fruits);

// Output the removed element and the updated array
echo "Removed element: " . $last_fruit . "<br>";
print_r($fruits);

In this example, the array_pop() function is used to remove the last element "grape" from the $fruits array and store its value in the $last_fruit variable. The output would be:

Removed element: grape
Array
(
    [0] => apple
    [1] => banana
    [2] => orange
)

As you can see, the $fruits array no longer contains the "grape" element, which has been removed by the array_pop() function.

Conclusion

Using this tutorial, you learned how to remove and return the last element from an array in PHP. Check our other PHP tutorials to learn more.

Great! Next, complete checkout for full access to GeekBits.
Welcome back! You've successfully signed in.
You've successfully subscribed to GeekBits.
Success! Your account is fully activated, you now have access to all content.
Success! Your billing info has been updated.
Your billing was not updated.