PHP array_pop() Tutorial 🎯

beginner
25 min

PHP array_pop() Tutorial 🎯

Welcome to our comprehensive guide on the array_pop() function in PHP! In this lesson, we'll learn what array_pop() is, why we use it, and how to effectively implement it in your projects. Let's dive right in!

Understanding array_pop() πŸ“

array_pop() is a built-in PHP function that removes the last element from an array and returns that element. It's incredibly useful when you want to remove the last item in an array and access it at the same time.

Syntax πŸ“

Here's the basic syntax of the array_pop() function:

php
array array_pop( array &$input_array );

As you can see, array_pop() only accepts one argument – the array you want to modify.

Example 1: Removing the last element from an array βœ…

Let's create an array and remove its last element using array_pop().

php
// Create an array $fruits = array("apple", "banana", "orange", "grape"); // Use array_pop() to remove the last fruit $last_fruit = array_pop($fruits); // Print the last fruit echo "The last fruit is: " . $last_fruit; // Print the updated array echo "\nUpdated array: " . print_r($fruits, true);

When you run this code, the output will be:

The last fruit is: grape Updated array: Array ( [0] => apple [1] => banana [2] => orange )

Example 2: Using array_pop() in a practical scenario βœ…

In this example, we'll use array_pop() to build a simple shopping cart system.

php
// Create an empty cart $cart = array(); // Add items to the cart $cart[] = "Apple"; $cart[] = "Banana"; $cart[] = "Orange"; $cart[] = "Grapes"; // Print the cart echo "Your cart:\n"; print_r($cart); // Remove the last item from the cart $last_item = array_pop($cart); // Print the updated cart echo "\nAfter removing the last item:\n"; print_r($cart);

The output will be:

Your cart: Array ( [0] => Apple [1] => Banana [2] => Orange [3] => Grapes ) After removing the last item: Array ( [0] => Apple [1] => Banana [2] => Orange )

Quiz πŸ’‘

Quick Quiz
Question 1 of 1

What does the `array_pop()` function do in PHP?

We hope you found this tutorial on PHP's array_pop() function helpful and informative. In the next lesson, we'll explore other useful array functions in PHP! πŸš€ Happy coding!