PHP array_pop: Remove and Return the Last Element of an Array

php array pop function

The array_pop function in PHP gives you a direct way to take the last element from an array.

Understand the array_pop Function in PHP

The array_pop in PHP removes the last value from an array. It helps when you want to handle lists where only the last value is important, and it also keeps the rest of the array.

Here is the syntax:

array_pop(array &$array): mixed

This function takes only one array and removes its last element, then returns that element. If the array is empty, it will return a null value.

Here is a quick example:

$fruits = ["apple", "banana", "orange"];
$lastFruit = array_pop($fruits);
print( $lastFruit ); // orange

This prints orange because it is the last element.

The array_pop function affects the original array, not just a copy. Because the array is passed by reference.

Here is the output of the original array if you use print_r($fruits):

Array
(
[0] => apple
[1] => banana
)

When you use array_pop():

  • The array must exist; otherwise, PHP will throw an error.
  • If the array exists but it has no elements inside it, then array_pop() will return NULL.

This is an example for another data type with array_pop instead of an array:

class Machine {}
$machine = new Machine();
array_pop($machine); // This throws fatal error in PHP

A Fatal Error output:

PHP Fatal error:  Uncaught TypeError: array_pop(): Argument #1 ($array) must be of type array, Machine given in /index.php:3
Stack trace:

Here, I pass an empty array to show you the result:

$array = [];
$val =  array_pop($array);
var_dump( $val ); // null

Here is another example with an associative array:

$user = ["name" => "Ali", "age" => 25, "city" => "Riyadh"];
$last = array_pop($user);

echo $last;   // Riyadh
print_r($user);

The output:

Riyadh
["name" => "Ali", "age" => 25]

Use array_pop with Nested Arrays

If the last element is an array, then the output will be an array. Here is an example:

$data = [[1, 2], [3, 4], [5, 6]];
$last = array_pop($data);

print_r($last);
print_r($data); 

The output:

[5, 6]
[[1, 2], [3, 4]]

Examples of the array_pop in PHP

The Stack Operation:

$stack = [];
array_push($stack, "first");
array_push($stack, "second");
array_push($stack, "third");

$last = array_pop($stack);
print_r($last);
print_r($stack);

The output:

third
Array
(
[0] => first
[1] => second
)

The array_pop acts like a stack pop and removes the last pushed element. It keeps the order of the rest.

Remove Last Value from Multidimensional Array:

$matrix = [
    [1, 2],
    [3, 4],
    [5, 6]
];

$lastRow = array_pop($matrix);
print_r($lastRow);
print_r($matrix);

The output:

Array
(
[0] => 5
[1] => 6
)
Array
(
[0] => Array
(
[0] => 1
[1] => 2
)

[1] => Array
(
[0] => 3
[1] => 4
)
)

Here, it removes the last nested array from the multidimensional array and keeps the earlier rows.

Remove Last Key-Value from Associative Array:

$user = [
    "id" => 101,
    "name" => "Sara",
    "role" => "Admin"
];

$last = array_pop($user);
print_r($last);
print_r($user);

The output:

Admin
Array
(
[id] => 101
[name] => Sara
)

This removes the last key-value pair from an associative array and gives back the value of that pair.

Use array_pop with an Array Returned from a Function ( PHP Notice ):

function getTasks() {
    return ["Task1", "Task2", "Task3", "Task4"];
}

$lastTask = array_pop(getTasks()); // PHP Notice
print($lastTask);

The output:

Task4
PHP Notice: Only variables should be passed by reference in /HelloWorld.php on line 7

Here, array_pop throws a notice because it requires a variable by reference, not a direct function return, even though it still returns the last element.

So, to make it work, fix it with this code:

function getTasks() {
    return ["Task1", "Task2", "Task3", "Task4"];
}

$tasks = getTasks();
$lastTask = array_pop($tasks);

print_r($lastTask);
print_r($tasks);

Here is the correct output:

Task4
Array
(
[0] => Task1
[1] => Task2
[2] => Task3
)

Wrapping Up

You learned what array_pop is and why it was added in PHP. You also saw the syntax and examples with associative and nested arrays.

Here is a quick recap:

  • array_pop removes the last element from an array and returns it.
  • It changes the original array by reference.
  • If the array is empty, the function returns NULL.

FAQs

How to get the last element of a PHP array?

You can use the array_pop to get the last item in an array. Here is an example:
$array = [10, 20, 30, 40, 50]; 
$last = array_pop($array);
echo $last;

How to remove the last element of a PHP array?

You can remove it with array_pop:
$array = [10, 20, 30, 40]; 
$removed = array_pop($array); 
echo $removed; 
print_r($array); 
This removes and returns the last item.

What happens if you use array_pop on an empty array?

It returns NULL if the array is empty. here is an example:
$array = []; 
$removed = array_pop($array); 
var_dump($removed); 

Similar Reads

PHP $_COOKIE: Securely Store and Manage Data

Ever notice how some websites just seem to "know" you? That’s thanks to cookies! When you’re working with PHP, $_COOKIE becomes a…

PHP While Loop: Iterating Through Code Blocks

The PHP “while” loop is a simple tool that repeatedly runs a block of code as long as a certain…

PHP Type Hints: Ensuring Data Integrity

PHP-type hinting is something that keeps your code in check and helps your functions receive just the right types of…

PHP Spaceship Operator

If you are new to the PHP Spaceship Operator, then let me tell you, you're in for a treat. This…

PHP File Inclusion: require, include, require_once, include_once

PHP offers four main functions to include files: require, require_once, include, and include_once. Each one gives you a similar purpose…

OOP Interface PHP: How to Set Rules for Classes

PHP developers relied on class inheritance to share functionality before the OOP interface, but this approach had limits. It solves…

PHP Callable & Callback: Pass a Function to Another

The callback in PHP lets you pass functions as arguments and reuse code. It helps you to control how tasks…

How to Insert Data into MySQL with PHP

pplications. Such As as From registering new users to collecting form submissions and storing product details. Things like adding a…

PHP htmlspecialchars Function: Prevent XSS in HTML Output

A PHP script can break the page or allow code injection if it outputs user input directly into HTML. The…

PHP DOMDocument: XML DOM Parser Guide

In PHP, if you're working with XML files, you’ll probably work with DOMDocument. It is a powerful class, enabling you…

Previous Article

PHP array_rand() Function: Usage & Examples

Next Article

PHP array_chunk(): Split Arrays into Manageable Parts

Write a Comment

Leave a Comment

Your email address will not be published. Required fields are marked *


Subscribe to Get Updates

Get the latest updates on Coding, Database, and Algorithms straight to your inbox.
No spam. Unsubscribe anytime.