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

PHP - Ds Sequence::last() Function



The PHP Ds\Sequence::last() function is used to retrieve the last value in a sequence. If the current sequence is empty ([]), this function will throw an "UnderflowException".

Syntax

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

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

Parameters

This function does not accept any parameter.

Return value

This function returns the last value in a sequence.

Example 1

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

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

Output

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

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

Example 2

Following is another example of the PHP Ds\Sequence::last() function. We use this function to retrieve the last value in this sequence (['a', 'e', 'i', 'o', 'u']) −

<?php 
   $seq = new \Ds\Set(['a', 'e', 'i', 'o', 'u']); 
   echo "The sequence elements are: \n";
   print_r($seq);
   echo "The last element in a sequence is: ";
   #using last() function
   print_r($seq->last());
?>

Output

The above program generates the following output −

The sequence elements are:
Ds\Set Object
(
    [0] => a
    [1] => e
    [2] => i
    [3] => o
    [4] => u
)
The last element in a sequence is: u

Example 3

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

<?php 
   $seq = new \Ds\Vector([]); 
   echo "The sequence elements are: \n";
   print_r($seq);
   echo "The last element in a sequence is: ";
   #using last() function
   print_r($seq->last());
?>

Output

Once the above program is executed, it throws the following exception −

The sequence elements are:
Ds\Vector Object
(
)
The last element in a sequence is: PHP Fatal error:  Uncaught UnderflowException:
Unexpected empty state in C:\Apache24\htdocs\index.php:7
Stack trace:
#0 C:\Apache24\htdocs\index.php(7): Ds\Vector->last()
#1 {main}
  thrown in C:\Apache24\htdocs\index.php on line 7
php_function_reference.htm
Advertisements