PHP array_pop

Summary: in this tutorial, you will learn how to use the PHP array_pop() function to remove an element from the end of an array.

Introduction to the PHP array_pop() function #

The array_pop() function removes an element from the end of an array and returns that element.

Here’s the syntax of the array_pop() function:

array_pop ( array &$array ) : mixedCode language: PHP (php)

In the syntax, the $array is the input array from which to return the last element.

If the input array is empty, the array_pop() function returns null.

Note that the array_pop() function modifies the input array.

PHP array_pop() function example #

The following example shows how to use the array_pop() function to remove the last element of an array:

<?php

$numbers = [1, 2, 3];

$last_number = array_pop($numbers);

echo $last_number . '<br>'; // 3

print_r($numbers);Code language: PHP (php)

Try it

Output:

3
Array ( [0] => 1 [1] => 2 )Code language: PHP (php)

How it works.

  • First, define an array with three numbers 1, 2, and 3.
  • Second, remove the last element of the $numbers array and assign it to the $last_number variable. The $last_number is 3.
  • Third, show the $last_number and the elements of the $numbers array.

Removing an element from an associative array #

The following example shows how to use the array_pop() function to remove the last element of an associative array:

<?php

$scores = [
    "John" => "A",
    "Jane" => "B",
    "Alice" => "C"
];

$score = array_pop($scores);

echo $score;
print_r($scores);Code language: PHP (php)

Try it

Output:

C
Array ( [John] => A [Jane] => B )Code language: PHP (php)

In this example, the array_pop() function remove the last element of the $scores array regardless of the key. It returns the value of that element, which is "C".

Summary #

  • Use the PHP array_pop() function to remove the last element of an array.
Did you find this tutorial useful?