PHP - Ds Set::last() Function
The PHP Ds\Set::last() function is used to retrieve the last value of the current set. It does not accept any index value to retrieve an element; it simply returns the last element of the set.
If the current set is empty, this function throws an "UnderflowException" exception.
Syntax
Following is the syntax of the PHP Ds\Set::last() function −
public Ds\Set::last(): mixed
Parameters
This function does not accept any parameter.
Return value
This function returns the last value in a set.
Example 1
The following program demonstrates the usage of the PHP Ds\Set::last() function.
<?php $set = new \Ds\set([11, 121, 12121, 1212121]); echo "The set elements are: "; print_r($set); echo "The last element of the set is: "; print_r($set->last()); ?>
Output
The above program displays the last value of this set is "1212121".
The set elements are: Ds\Set Object
(
[0] => 11
[1] => 121
[2] => 12121
[3] => 1212121
)
The last element of the set is: 1212121
Example 2
The following is another example of the PHP Ds\Set::last() function. We use this function to retrieve the last element of this set (["Welcome", "to", "Tutorials", "point"]).
<?php $set = new \Ds\set(["Welcome", "to", "Tutorials", "point"]); echo "The set elements are: \n"; print_r($set); echo "The last element of the set is: "; print_r($set->last()); ?>
Output
The above program returns the last element as a "point".
The set elements are:
Ds\Set Object
(
[0] => Welcome
[1] => to
[2] => Tutorials
[3] => point
)
The last element of the set is: point
Example 3
If the current set is empty, the last() function throws an "UnderflowException" exception.
<?php $set = new \Ds\set([]); echo "The set elements are: "; print_r($set); echo "The last element of the set is: "; print_r($set->last()); ?>
Output
On executing the above program, it will throw the following error −
The set elements are: Ds\Set Object
(
)
The last element of the set 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\Set->last()
#1 {main}
thrown in C:\Apache24\htdocs\index.php on line 6