PHP array_pop() Function

What is PHP array_pop() Function?

If you want to remove the last element of an array, use array_pop() function. You also get this element as the return value of the function.

Syntax:

array_pop(array)

Parameters:

The Function has 1 required parameter-

array (Required): It is the array from where the last element will be omitted.

Return Values:

  • As the function modifies the array by removing the last element, after running the function, the input array itself now has all the elements except the last one. See example 1.
  • The function returns the last element that has been removed from the array. See example 2
  • If the supplied array is empty, PHP returns NULL. See example 3.

Examples:

Example 1:

<pre>
<?php
$language = ["PHP", "Python", "Java", "HTML", "CSS"];
array_pop($language);
print_r($language);
?>
</pre>

Output:

Array
(
[0] => PHP
[1] => Python
[2] => Java
[3] => HTML
)

Example 2

<?php
$language = ["PHP", "Python", "Java", "HTML", "CSS"];
$modified_element = array_pop($language);
echo "The removed element is: " . $modified_element;
?>

Output:

The removed element is: CSS

Example 3:

<?php
$language = [];
$modified_element = array_pop($language);
echo "The removed element is: "; 
var_dump($modified_element);
?>

Output:

The removed element is: NULL

Example 4:

<?php
$language = ["PHP", "Python", "Java", "HTML", "CSS"];
array_pop($language);
echo "The internal pointer is now pointing to the key: " . key($language);
?>

Output:

The internal pointer is now pointing to the key: 0

Notes on array_pop() Function:

After running the function, it reset the internal pointer to the first element by running reset() function. See example 4.

PHP Version Support:

PHP 4, PHP 5, PHP 7, PHP 8

Summary: PHP array_pop() Function

The array_pop() function is a built-in PHP function and part of the PHP’s array functions. It is a useful function to remove the last element from an array.

Reference: