PHP - Ds\Stack::pop() Function



The PHP Ds\Stack::pop() function is used to remove and retrieve the value at the top of the current stack.

As we know the stack follows the LIFO (Last In, First Out), the last element that was added will be removed, which is the element at the top of the stack. If the stack is empty ([]), this function will throw an "UnderflowException".

Syntax

Following is the syntax of the PHP Ds\Stack::pop() function −

public Ds\Stack::pop(): mixed

Parameters

This function does not accept any parameter.

Return value

This function returns the removed value at the top of a stack.

Example 1

The following program demonstrates the usage of the PHP Ds\Stack::pop() function −

<?php 
   $stack = new \Ds\Stack([10, 20, 30]);
   echo "The original stack elements are: \n";
   print_r($stack);
   echo "The stack elements after called pop() function: \n";
   #using pop() function
   $stack->pop();
   print_r($stack);
?>

Output

The above program produces the following output −

The original stack elements are:
Ds\Stack Object
(
    [0] => 30
    [1] => 20
    [2] => 10
)
The stack elements after called pop() function:
Ds\Stack Object
(
    [0] => 20
    [1] => 10
)

Example 2

Following is another example of the PHP Ds\Stack::pop() function. We use this function to remove and retrieve the removed element of the current instance.

<?php 
   $stack = new \Ds\Stack(['a', 'e', 'i']);
   $stack->push('o');
   $stack->push('u');
   echo "The original stack elements are: \n";
   print_r($stack);
   #using pop() function
   echo "The removed elements: ";
   print_r($stack->pop());
   echo "\nThe stack elements after pop() function called: \n";
   print_r($stack);
?>

Output

After executing the above program, the following output will be displayed:

The original stack elements are:
Ds\Stack Object
(
    [0] => u
    [1] => o
    [2] => i
    [3] => e
    [4] => a
)
The removed elements: u
The stack elements after pop() function called:
Ds\Stack Object
(
    [0] => o
    [1] => i
    [2] => e
    [3] => a
)

Example 3

If the current stack is empty ([]), this function will throw an "UnderflowException".

<?php 
   $stack = new \Ds\Stack([ ]);
   echo "The original stack elements are: \n";
   print_r($stack);
   #using pop() function
   echo "The removed elements: ";
   print_r($stack->pop());
   echo "\nThe stack elements after pop() function called: \n";
   print_r($stack);
?>

Output

The above program throws the following exception −

The original stack elements are:
Ds\Stack Object
(
)
The removed elements: PHP Fatal error:  
Uncaught UnderflowException: Unexpected empty state in C:\Apache24\htdocs\index.php:7
Stack trace:
#0 C:\Apache24\htdocs\index.php(7): Ds\Stack->pop()
#1 {main}
  thrown in C:\Apache24\htdocs\index.php on line 7
php_function_reference.htm
Advertisements