PHP array_pop() function


The array_pop() function in PHP is used to remove the last element from an array and return that element. This function modifies the original array by reducing its size and is particularly useful when you need to work with stack-like structures (Last In, First Out - LIFO).

Syntax:

array_pop(array &$array): mixed

Parameters:

  • $array: The input array from which the last element will be removed (passed by reference).

Return Value:

  • Returns the value of the last element of the array, or null if the array is empty. The original array is modified, and its last element is removed.

Example 1: Basic Usage

In this example, we demonstrate how to use array_pop() to remove the last element from an array.

<?php $array = [1, 2, 3, 4, 5]; $lastElement = array_pop($array); echo "Last Element: " . $lastElement . "\n"; print_r($array); ?>

Output:

Last Element: 5 Array ( [0] => 1 [1] => 2 [2] => 3 [3] => 4 )

Here, 5 is removed from the original array, and the remaining elements are printed.

Example 2: Using array_pop() on an Empty Array

If you call array_pop() on an empty array, it will return null.

<?php $array = []; $lastElement = array_pop($array); echo "Last Element: " . ($lastElement === null ? 'null' : $lastElement) . "\n"; print_r($array); ?>

Output:

Last Element: null Array ( )

In this case, the original array remains empty, and null is returned.

Example 3: Working with Multidimensional Arrays

You can also use array_pop() with multidimensional arrays. However, it will only remove the last element of the specified array, not any nested arrays.

<?php $array = [ ["name" => "Alice"], ["name" => "Bob"], ["name" => "Charlie"] ]; $lastElement = array_pop($array); print_r($lastElement); print_r($array); ?>

Output:

Array ( [name] => Charlie ) Array ( [0] => Array ( [name] => Alice ) [1] => Array ( [name] => Bob ) )

Here, the last element (["name" => "Charlie"]) is removed from the array, and the remaining elements are printed.

Example 4: Using in a Loop

You can repeatedly call array_pop() in a loop to remove elements from the end of an array until it is empty.

<?php $array = [1, 2, 3, 4, 5]; while (!empty($array)) { echo array_pop($array) . "\n"; } ?>

Output:

5 4 3 2 1

In this example, all elements are popped from the array and printed in reverse order.

Practical Usage:

  • array_pop() is useful for:
    • Implementing stack data structures (LIFO).
    • Removing elements from the end of an array when the order of elements matters.
    • Managing collections of items where you need to track the last added item.

Summary:

  • array_pop($array) removes and returns the last element from the specified array.
  • If the array is empty, it returns null.
  • The function modifies the original array, making it a straightforward way to manage arrays in a LIFO manner.
  • It can be used effectively with both simple and multidimensional arrays.