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 ) : mixed
Code 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; // 3
print_r($numbers);
Code language: HTML, XML (xml)
Output:
3
Array
(
[0] => 1
[1] => 2
)
Code language: PHP (php)
How it works.
- First, define an array that has 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.
Summary
- Use the PHP
array_pop()
function to remove the last element of an array.
Did you find this tutorial useful?