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:
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.
Output:
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
.
Output:
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.
Output:
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.
Output:
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.