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 Resource Type | How the get_resource_type() Works

In this tutorial, I will explain what does mean the PHP resource and we are going to cover all PHP…

PHP filter_var_array: How to Validate Multiple Inputs

The filter_var_array() appeared to make input validation simple and sanitization in PHP. It handles multiple inputs with different filters was…

Understanding the PHP Operator Precedence

The PHP operator precedence refers to when doing a calculation for three or more numbers, they are calculating its values…

PHP array_change_key_case: Change Array Key Cases

The array_change_key_case function in PHP changes all array keys to lowercase or uppercase for consistent data use. Understand the array_change_key_case…

PHP $_SESSION: Secure Your Web Applications in PHP

It’s very important to remember user data for each session when building web applications. This enables a high level of…

How to Select Data Using PHP and MySQL?

In this article, You will understand everything you need to know about how to use PHP to select data from…

PHP IF Statement: A Guide to Conditional Logic

The IF statement in PHP helps to see if a condition is true or not. If it is true, it…

PHP Singleton Pattern: How to Use with Examples

The PHP singleton design pattern makes sure that the class has only one instance and provides a global access point…

PHP Class Destructor: How It Works with Examples

A destructor in a PHP class runs when an object is no longer needed. It frees resources and cleans up…

PHP implode Function: Join Array Values into a String

The implode function in PHP appeared to solve a common need—joining array elements into a single string. It helps format…

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.