The array_pop()
function in PHP is used to remove and return the last element of an array.
📘 Syntax:
mixed array_pop(array &$array)
- Parameter: The array from which the last element will be popped.
- Return Value: The value of the last element, or
NULL
if the array is empty.
- Note: The original array is modified (the last element is removed).
✅ Example 1: Basic usage
$fruits = ["apple", "banana", "cherry"];
$lastFruit = array_pop($fruits);
echo $lastFruit; // Output: cherry
print_r($fruits); // Output: Array ( [0] => apple [1] => banana )
✅ Example 2: Popping from a numeric array
$numbers = [10, 20, 30, 40];
$popped = array_pop($numbers);
echo $popped; // Output: 40
print_r($numbers); // Output: Array ( [0] => 10 [1] => 20 [2] => 30 )
✅ Example 3: Popping from an associative array
$person = [
"name" => "John",
"age" => 30,
"city" => "New York"
];
$removed = array_pop($person);
echo $removed; // Output: New York
print_r($person);
// Output: Array ( [name] => John [age] => 30 )
Even with associative arrays, array_pop()
still removes the last element based on insertion order, not by key name.
🛑 Note:
If you use array_pop()
on an empty array, it returns NULL
:
$empty = [];
$result = array_pop($empty);
var_dump($result); // Output: NULL