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

PHP - Ds Sequence::shift() Function



The PHP Ds\Sequence::shift() function is used to remove and retrieve the first value in a sequence. The Ds\Sequence class provides another function named remove(), which removes an element at the specified index, and if the index is 0, it removes the first value.

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

Syntax

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

abstract public Ds\Sequence::shift(): mixed

Parameters

This function does not accept any parameter.

Return value

This function returns the first value that was removed.

Example 1

The following is the basic example of the PHP Ds\Sequence::shift() function −

<?php 
   $seq = new \Ds\Vector([10, 20, 30, 40, 50]);
   echo "The sequence elements are: \n";
   print_r($seq);
   echo "The deleted element: ";
   #using shift() function
   print_r($seq->shift());
?>

Output

The above program produces the following output −

The sequence elements are:
Ds\Vector Object
(
    [0] => 10
    [1] => 20
    [2] => 30
    [3] => 40
    [4] => 50
)
The deleted element: 10

Example 2

Following is another example of the PHP Ds\Sequence::shift() function. We use this function to remove and retrieve the first element of this sequence (["Raja", "Jai", "Adithya"]) −

<?php 
   $seq = new \Ds\Vector(["Raja", "Jai", "Adithya"]);
   echo "The original sequence: \n";
   print_r($seq);
   echo "The deleted elements are: ";
   for($i = 0; $i<3; $i++){
	   print_r($seq->shift()." ");
   }
   echo "\nThe sequence after shift: \n";
   print_r($seq);
?>

Output

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

The original sequence:
Ds\Vector Object
(
    [0] => Raja
    [1] => Jai
    [2] => Adithya
)
The deleted elements are: Raja Jai Adithya
The sequence after shift:
Ds\Vector Object
(
)

Example 3

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

<?php 
   $seq = new \Ds\Vector([]);
   echo "The original sequence: \n";
   print_r($seq);
   echo "The deleted elements are: ";
   print_r($seq->shift());
   echo "\nThe sequence after shift: \n";
   print_r($seq);   
?>

Output

Once the above program is executed, it generates the following output −

The original sequence:
Ds\Vector Object
(
)
The deleted elements are: 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