PHP - Ds Sequence::pop() Function
The PHPDs\Sequence::pop()function removes the last value in a sequence and returns the previously removed value as a result.
If the current sequence is empty ([]), this function will throw an "UnderflowException". If you try to print the sequence, the last element will be removed from it.
Syntax
Following is the syntax of the PHP Ds\Sequence::pop() function −
abstract public Ds\Sequence::pop(): mixed
Parameters
This function does not accept any parameter.
Return value
This function returns the last removed value.
Example 1
The following is the basic example of the PHP Ds\Sequence::pop() function −
<?php $seq = new \Ds\Vector( [1, 2, 3, 4, 5] ); echo "The sequence elements are: \n"; print_r($seq); echo "The last removed element: "; #using pop() function print_r($seq->pop()); ?>
Output
The above program produces the following output −
The sequence elements are:
Ds\Vector Object
(
[0] => 1
[1] => 2
[2] => 3
[3] => 4
[4] => 5
)
The last removed element: 5
Example 2
Pop all the elements one by one using the pop() function within the for-loop.
Following is another example of the PHPDs\Sequence::pop()function. We use this function to remove elements from the last of this sequence (['a', 'e', 'i', 'o', 'u']) −
<?php
$seq = new \Ds\Vector(['a', 'e', 'i', 'o', 'u']);
echo "The sequence elements are: \n";
print_r($seq);
echo "The removed elements are: \n";
for($i = 0; $i < 5; $i++){
print_r($seq->pop()."\n");
}
echo "The sequence after pop each elements: \n";
print_r($seq);
?>
Output
After executing the above program, the following output will be displayed −
The sequence elements are:
Ds\Vector Object
(
[0] => a
[1] => e
[2] => i
[3] => o
[4] => u
)
The removed elements are:
u
o
i
e
a
The sequence after pop each elements:
Ds\Vector Object
(
)
Example 3
If the current sequence is empty ([]), the pop() function will throw an "UnderflowException" −
<?php $seq = new \Ds\Vector([]); echo "The sequence elements are: \n"; print_r($seq); echo "The removed element is: "; print_r($seq->pop()); echo "\nThe sequence after pop last element: \n"; print_r($seq); ?>
Output
Once the above program is executed, it throws the following exception −
The sequence elements are:
Ds\Vector Object
(
)
The removed element is: 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\Vector->pop()
#1 {main}
thrown in C:\Apache24\htdocs\index.php on line 6