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

PHP - Ds Vector::last() Function



The PHP Ds\Vector::last() function is used to retrieve the last value in a vector. This function throws an "UnderflowException" if the current vector is empty ([]).

The Ds\Vector class also provides a get() function that allows you to retrieve a value at a specified index. If you specify the index as "count() - 1", you can retrieve the last element in a vector. The count() function returns size of vector.

Syntax

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

public mixed Ds\Vector::last( void )

Parameters

This function does not accept any parameter.

Return value

This function returns the last value in a vector.

Example 1

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

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

Output

The above program generates the following output −

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

Example 2

Following is another example of the PHP Ds\Vector::last() function. We use this function to retrieve the last element of this vector (["Tutorials", "Point", "Tutorix", "e-learning"]) −

<?php 
   $vector = new \Ds\Vector(
   ["Tutorials", 
   "Point", 
   "Tutorix", 
   "e-learning"]);
   echo "The vector elements are: \n";
   print_r($vector);   
   echo("The last element of vector: "); 
   var_dump($vector->last());
?>

Output

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

The vector elements are:
Ds\Vector Object
(
    [0] => Tutorials
    [1] => Point
    [2] => Tutorix
    [3] => e-learning
)
The last element of vector: string(10) "e-learning"

Example 3

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

<?php 
   $vector = new \Ds\Vector([]);
   echo "The vector elements are: \n";
   print_r($vector);   
   echo("The last element of vector: "); 
   var_dump($vector->last());
?>

Output

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

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