Encodera

Thanks for reading!

Donate to the site — we work hard for you.

PHP reference

array_pop

Removes the last element of an array and returns it.

Available since: PHP 4

Syntax

array_pop(array &$array): mixed

Parameters

ParameterTypeDescription
$arrayarrayThe array to take the element from. It is passed by reference and modified.

Return value

mixedThe removed element, or `null` if the array is empty.

Examples

Taking the last element:

<?php
 
$stack = ['a', 'b', 'c'];
$last = array_pop($stack);
 
echo $last, "\n";
echo implode(', ', $stack);

Output:

c
a, b

array_shift() does the same with the first element:

<?php
 
$queue = ['a', 'b', 'c'];
$first = array_shift($queue);
 
echo $first, "\n";
echo implode(', ', $queue);

Output:

a
b, c

Notes

The reverse operations are array_push() (append) and array_unshift() (prepend).

See also

  • array_slice — Returns part of an array.
  • count — Returns the number of elements in an array.

Related recipes

In the tutorial

  • Arrays — Lists and associative arrays in PHP — creating, changing, iterating and useful functions.

Thanks for reading!

Donate to the site — we work hard for you.