Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

PHP - Ds Vector::shift() Function



The PHPDs\Vector::shift()function is used to remove and retrieve the first value from a vector. This function modifies the original vector and returns the first removed element.

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

Syntax

Following is the syntax of the PHP Ds\Vector::shift() function −

public mixed Ds\Vector::shift( void )

Parameters

This function does not accept any parameter.

Return value

This function returns the first value that was removed.

Example 1

The following program demonstrates the usage of the PHP Ds\Vector::shift() function −

<?php
   $vector = new \Ds\Vector(["a", "b", "c"]);
   echo "The original vector: \n";
   print_r($vector);
   echo "The updated vector: ";
   print_r($vector->shift());
?>

Output

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

The original vector:
Ds\Vector Object
(
    [0] => a
    [1] => b
    [2] => c
)
The updated vector: a

Example 2

Following is another example of the PHP Ds\Vector::shift() function. We use this function to remove and retrieve the first value of this vector ([10, 20, 30, 40, 50]) −

<?php
   $vector = new \Ds\Vector([10, 20, 30, 40, 50]);
   echo "The original vector: \n";
   print_r($vector);
   echo "The removed values are: ";
   print_r($vector->shift());
   echo " ";
   print_r($vector->shift());
   echo "\nThe vector after removing first two values: \n";
   print_r($vector);
?>

Output

The above program produces the following output −

The original vector:
Ds\Vector Object
(
    [0] => 10
    [1] => 20
    [2] => 30
    [3] => 40
    [4] => 50
)
The removed values are: 10 20
The vector after removing first two values:
Ds\Vector Object
(
    [0] => 30
    [1] => 40
    [2] => 50
)

Example 3

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

<?php
   $vector = new \Ds\Vector([]);
   echo "The original vector: \n";
   print_r($vector);
   echo "The removed value is: ";
   print_r($vector->shift());
   echo "\nThe vector after removing first two values: \n";
   print_r($vector);
?>

Output

Once the above program is executed, it will generate the following output −

The original vector:
Ds\Vector Object
(
)
The removed value 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->shift()
#1 {main}
  thrown in C:\Apache24\htdocs\index.php on line 6
php_function_reference.htm
Advertisements