PHP - Ds Vector::pop() Function



The PHP Ds\Sequence::pop() function is used to remove the last value from a vector, and the removed value will be returned in the result.

This function affects the original vector, which means if you try to print the vector after calling the pop() function, the vector will not have the last element in it.

It throws an UnderflowException if the current vector is empty ([]).

Syntax

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

public Ds\Vector::pop(): mixed

Parameters

This function does not accept any parameter.

Return value

This function returns the removed last value.

Example 1

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

<?php 
   $vector = new \Ds\Vector([10, 20, 30, 40, 50]);
   echo("The original vector elements: \n"); 
   print_r($vector);
   echo("The last element in vector is: ");
   print_r($vector->pop()); 
?>

Output

The above program produces the following output −

The original vector elements:
Ds\Vector Object
(
    [0] => 10
    [1] => 20
    [2] => 30
    [3] => 40
    [4] => 50
)
The last element in vector is: 50

Example 2

Following is another example of the PHP Ds\Sequence::pop() function. We use this function to remove and retrieve the last value of this vector (["Tutorials", "Point", "India"]) −

<?php 
   $vector = new \Ds\Vector(["Tutorials", "Point", "India"]);
   echo "The vector elements are: \n";
   print_r($vector);
   echo "The removed last element in vector: ";
   print_r($vector->pop());
   echo "\nThe updated vector is: \n";
   print_r($vector);
?>

Output

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

The vector elements are:
Ds\Vector Object
(
    [0] => Tutorials
    [1] => Point
    [2] => India
)
The removed last element in vector: India
The updated vector is:
Ds\Vector Object
(
    [0] => Tutorials
    [1] => Point
)

Example 3

If the current vector is empty ([]), the pop() function will throw an "UnderflowException" −

<?php 
   $vector = new \Ds\Vector([]);
   echo "The vector elements are: \n";
   print_r($vector);
   echo "The removed last element in vector: ";
   print_r($vector->pop());
   echo "\nThe updated vector is: \n";
   print_r($vector);
?>

Output

Once the above program is executed, it will throw the following exception −

The vector elements are:
Ds\Vector Object
(
)
The removed last element in vector: 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
php_function_reference.htm
Advertisements