Open In App

PHP array_pop() Function

Last Updated : 20 Jun, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

This inbuilt function of PHP is used to delete or pop out and return the last element from an array passed to it as parameter. It reduces the size of the array by one since the last element is removed from the array.

Syntax:

array_pop($array)

Parameters: The function takes only one parameter $array, that is the input array and pops out the last element from it, reducing the size by one.

Return Value: This function returns the last element of the array. If the array is empty or the input parameter is not an array, then NULL is returned.

Note: This function resets the (reset()) the array pointer of the input array after use.

Examples:

Input : $array = (1=>"ram", 2=>"krishna", 3=>"aakash");
Output : aakash

Input : $array = (24, 48, 95, 100, 120);
Output : 120

Below programs illustrate the array_pop() function in PHP:

Example 1




<?php
// PHP code to illustrate the use of array_pop()
  
$array = array(1=>"ram", 2=>"krishna", 3=>"aakash");
  
print_r("Popped element is ");
echo array_pop($array);
  
print_r("\nAfter popping the last element, ".
                "the array reduces to: \n");
print_r($array);
?>


Output:

Popped element is aakash
After popping the last element, the array reduces to: 
Array
(
    [1] => ram
    [2] => krishna
)

Example 2




<?php
$arr = array(24, 48, 95, 100, 120);
  
print_r("Popped element is ");
echo array_pop($arr);
  
print_r("\nAfter popping the last element, ".
                "the array reduces to: \n");
print_r($arr);
?>


Output:

Popped element is 120
After popping the last element, the array reduces to: 
Array
(
    [0] => 24
    [1] => 48
    [2] => 95
    [3] => 10
)

Exception: An E_WARNING exception is thrown if a non-array is passed which is a runtime error or warning. This warning will not stop the execution of script.

Reference:
http://php.net/manual/en/function.array-pop.php



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads