0
0
PhpHow-ToBeginner · 3 min read

How to Use array_pop in PHP: Syntax and Examples

In PHP, array_pop removes the last element from an array and returns it. It modifies the original array by shortening it by one element.
📐

Syntax

The array_pop function takes one argument, the array you want to modify. It removes the last element from this array and returns that element.

  • array_pop(array &$array): mixed
  • $array: The array to remove the last element from. It is passed by reference and will be changed.
  • Returns the removed element or null if the array is empty.
php
array_pop(array &$array): mixed
💻

Example

This example shows how array_pop removes the last element from an array and returns it. The original array becomes shorter by one element.

php
<?php
$fruits = ['apple', 'banana', 'cherry'];
$lastFruit = array_pop($fruits);
echo "Removed fruit: $lastFruit\n";
echo "Remaining fruits: ";
print_r($fruits);
?>
Output
Removed fruit: cherry Remaining fruits: Array ( [0] => apple [1] => banana )
⚠️

Common Pitfalls

One common mistake is expecting array_pop to work on a copy of the array. Since it modifies the original array, you must pass the actual array variable.

Another pitfall is calling array_pop on an empty array, which returns null and does not cause an error.

php
<?php
// Wrong: passing array copy, original not changed
$numbers = [1, 2, 3];
array_pop($numbers); // works

// Right: original array is changed
$numbers = [1, 2, 3];
$last = array_pop($numbers);
echo $last; // 3
print_r($numbers); // [1, 2]

// Empty array case
$empty = [];
$last = array_pop($empty);
var_dump($last); // NULL
?>
Output
3 Array ( [0] => 1 [1] => 2 ) NULL
📊

Quick Reference

FunctionDescriptionReturnsModifies Array?
array_popRemoves last element from arrayLast element or null if emptyYes

Key Takeaways

array_pop removes and returns the last element of an array, modifying the original array.
Passing the array variable itself is necessary because array_pop changes the array by reference.
If the array is empty, array_pop returns null without error.
Use array_pop to easily get and remove the last item from a list.
Remember the original array becomes shorter after using array_pop.