PHP - Ds Deque::pop() Function
The PHP Ds\Deque::pop() function is used to remove the last element in the current deque and returns the last removed value of a deque. If the current deque is empty ([]), this function will throw an "UnderflowException" exception.
After invoking this function on the deque, the deque's size will be reduced by 1.
Syntax
Following is the syntax of the PHP Ds\Deque::pop() function −
public Ds\Deque::pop(): mixed
Patameters
This function does not accept any parameter.
Return value
This function returns the last removed value.
Example 1
The following program demonstrates the usage of the PHP Ds\Deque::pop() function −
<?php $deque = new \Ds\Deque([1, 2, 3, 4, 5]); echo "The deque elements are: \n"; print_r($deque); echo "The last removed element: "; #using pop() function print_r($deque->pop()); ?>
Output
After executing the above program, the following output will be displayed −
The deque elements are:
Ds\Deque Object
(
[0] => 1
[1] => 2
[2] => 3
[3] => 4
[4] => 5
)
The last removed element: 5
Example 2
Following is another example of the PHP Ds\Deque::pop() function. We use this function to remove the last element of this deque (["Hello","world","!"]) −
<?php $deque = new \Ds\Deque(["Hello","world","!"]); echo "The deque elements are:\n "; print_r($deque); echo "The last removed element: "; print_r($deque->pop()); echo "\nThe deque after remove last element: \n"; print_r($deque); ?>
Output
Once the above program is executed, it will display the output shown below −
The deque elements are:
Ds\Deque Object
(
[0] => Hello
[1] => world
[2] => !
)
The last removed element: !
The deque after remove last element:
Ds\Deque Object
(
[0] => Hello
[1] => world
)
Example 3
If the current deque is empty ([]), this function will throw an "UnderflowException" as follows:
<?php $deque = new \Ds\Deque([]); echo "The deque elements are:\n"; print_r($deque); echo "The last removed element: "; print_r($deque->pop()); echo "\nThe deque after remove last element: \n"; print_r($deque); ?>
Output
On executing the above program, it throws an exception as follows:
The deque elements are:
Ds\Deque Object
(
)
The last removed element: PHP Fatal error: Uncaught UnderflowException:
Unexpected empty state in C:\Apache24\htdocs\index.php:6
Stack trace:
#0 C:\Apache24\htdocs\index.php(6): Ds\Deque->pop()
#1 {main}
thrown in C:\Apache24\htdocs\index.php on line 6