PHP - Ds Map::last() Function



The PHP Ds\Map::last() function is used to retrieve the last pair in a map. The pairs refer to the keys and values of the map elements. This function returns an array containing the last key-value pair of the map.

This function throws an UnderflowException if the current map is empty, indicating there is no elements to retrieve.

Syntax

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

public Ds\Pair Ds\Map::last(); Ds\Pair

Parameters

This function does not accept any parameter.

Return value.

This function returns the last pair of a map.

Example 1

The following is the basic example of the PHP Ds\Map::last() function −

<?php 
   $map = new \Ds\Map([1, 2, 3]);
   echo "The map elements are: \n";
   print_r($map);
   echo "The last pair of the map: \n";
   #using last() function
   print_r($map->last()); 
?>

Output

The above program generates the following output −

The map elements are:
Ds\Map Object
(
    [0] => Ds\Pair Object
        (
            [key] => 0
            [value] => 1
        )

    [1] => Ds\Pair Object
        (
            [key] => 1
            [value] => 2
        )

    [2] => Ds\Pair Object
        (
            [key] => 2
            [value] => 3
        )

)
The last pair of the map:
Ds\Pair Object
(
    [key] => 2
    [value] => 3
)

Example 2

Following is another example of the PHP Ds\Map::last() function. We use this function to retrieve the last pair on this map (["Tutorials", "Point", "India"]) −

<?php 
   $map = new \Ds\Map(["Tutorials", "Point", "India"]);
   echo "The map elements are: \n";   
   print_r($map);
   echo "The last pair of the map: \b";
   #using last() function
   print_r($map->last()); 
?>

Output

After executing the above program, it will display the following output −

The map elements are:
Ds\Map Object
(
    [0] => Ds\Pair Object
        (
            [key] => 0
            [value] => Tutorials
        )

    [1] => Ds\Pair Object
        (
            [key] => 1
            [value] => Point
        )

    [2] => Ds\Pair Object
        (
            [key] => 2
            [value] => India
        )

)
The last pair of the map: \bDs\Pair Object
(
    [key] => 2
    [value] => India
)

Example 3

If the current map is empty, this function throws an "UnderflowException".

<?php 
   $map = new \Ds\Map([]); 
   echo "The map elements are: \n";
   print_r($map);
   echo "The last pair of a map: \n";
   #using the last() function
   print_r($map->last()); 
?>

Output

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

The map elements are:
Ds\Map Object
(
)
The last pair of a map:
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\Map->last()
#1 {main}
  thrown in C:\Apache24\htdocs\index.php on line 7
php_function_reference.htm
Advertisements