php

PHP array_pop() Function

array_pop() in PHP is used to remove the last value in the array. It will return the popped value. We can do this after performing a pop operation if we want to print the remaining elements present in an array. It takes an array input as a parameter.

Syntax:
array_pop(array_input)

Parameters:
array_input is the array

Let’s see examples to understand this concept better.

Example 1:
Let’s create an array with four values: ‘lotus’,’lilly’,’jasmine’,’rose’.

Use array_pop() to remove the last value from the array.

<?php
 
//create an array named Flower1 with 4 values.
$Flower=array('lotus','lilly','jasmine','rose');
 
echo 'Actual Array: ';
print_r($Flower);
 
//remove last value
echo 'Popped value: '.array_pop($Flower).'\n';
echo 'Final Array: ';
print_r($Flower);
 
?>

Output:

We can see that rose is removed from the array since it is the last value.

Example 2:
Let’s create an array with four key-values: ‘flower1’=>’lotus’,’flower2’=>’lilly’,’flower3’=>’jasmine’,’flower4’=>’rose’.

Use array_pop to remove the last key-value pair.

<?php
 
//create an array named Flower1 with 4 key-values.
$Flower=array('flower1'=>'lotus','flower2'=>'lilly','flower3'=>'jasmine','flower4'=>'rose');

 
echo 'Actual Array: ';
print_r($Flower);
 
//remove last value
echo 'Popped value: '.array_pop($Flower).'\n';
echo 'Final Array: ';
print_r($Flower);
 
?>

Output:

We can see that ‘flower4’=>’rose’ is removed from the array.

Example 3:
Let’s create an array with two nested arrays that have two values each: array(array(‘lotus’,’lilly’),array(‘carrot’,’tamarind’)) and pop the last nested array.

<?php
 
//create an array with 2 nested arrays that has 2 values each
$Flower=array(array('lotus','lilly'),array('carrot','tamarind'));

 
echo 'Actual Array: ';
print_r($Flower);
 
//remove last value
echo 'Popped value: '.'\n';
print_r(array_pop($Flower));
echo 'Final Array: ';
print_r($Flower);
?>

Output:

We can see that the last nested array is removed.

Conclusion

We saw how to pop the last element from the PHP array using the array_pop() function. It removes the last element and returns the popped element by taking the input array as a parameter. It is also possible to remove the last entire nested array from an array using array_pop().

About the author

Gottumukkala Sravan Kumar

B tech-hon's in Information Technology; Known programming languages - Python, R , PHP MySQL; Published 500+ articles on computer science domain