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

PHP - Ds Deque::last() Function



The PHP Ds\Deque::last() function is used to retrieve the last (or the first element starting from the right side) element in the current deque.

If the current deque is empty (or it has 0 elements), this function will throw an "UnderflowException" exception. Unlike the first() function, which returns the first element, this function returns the last element in the deque.

Syntax

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

public Ds\Deque::last(): mixed

Parameters

This function does not accept any parameter.

Return value

This function returns the last element in a deque.

Example 1

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

<?php
   $deque = new \Ds\Deque([1, 2, 3, 4]);
   echo "The deque elements are: \n";
   print_r($deque);
   echo "The last element is: ";
   print_r($deque->last());
?>

Output

The above program returns the last element of deque as:

The deque elements are:
Ds\Deque Object
(
    [0] => 1
    [1] => 2
    [2] => 3
    [3] => 4
)
The last element is: 4

Example 2

Following is another example of the PHP Ds\Deque::last() function. We use this function to retrieve the last element of this deque (["Welcome", "to", "Tutorials", "point"]) −

<?php
   $deque = new \Ds\Deque(["Welcome", "to", "Tutorials", "point"]);
   echo "The deque elements are: \n";
   print_r($deque);
   echo "The last element of a deque is: ";
   print_r($deque->last());
?>

Output

After executing the above program, the last element of the deque will be displayed −

The deque elements are:
Ds\Deque Object
(
    [0] => Welcome
    [1] => to
    [2] => Tutorials
    [3] => point
)
The last element of a deque is: point

Example 3

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

In the example below, we use the last() method to retrieve the last element of this empty deque([]). Since the deque is empty, it will throw an exception as follows:

<?php
   $deque = new \Ds\Deque([]);
   echo "The deque elements are: \n";
   print_r($deque);
   echo "The last element of the deque is: ";
   print_r($deque->last());
?>

Output

Once the above program is executed, it will throw an exception as:

The deque elements are:
Ds\Deque Object
(
)
The last element of the deque 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\Deque->last()
#1 {main}
  thrown in C:\Apache24\htdocs\index.php on line 6
Advertisements