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

PHP - Ds Vector::first() Function



The PHP Ds\Vector::first() function is used to retrieve the first 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 0, you can retrieve the first element in a vector.

Syntax

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

public Ds\Vector::first(): mixed

Parameters

This function does not accept any parameter.

Return value

This function return the first value in a vector.

Example 1

The following is the basic example of the PHP Ds\Vector::first() function −

<?php
   $vector = new \Ds\Vector([1, 2, 3, 4, 5]);
   echo "The vector elements are: \n";
   print_r($vector);
   echo("The first element of vector: "); 
   var_dump($vector->first());
?>

Output

The above program produces the following output −

The vector elements are:
Ds\Vector Object
(
    [0] => 1
    [1] => 2
    [2] => 3
    [3] => 4
    [4] => 5
)
The first element of vector: int(1)

Example 2

Following is another example of the PHP Ds\Vector::first() function. We use this function to retrieve the first element in this vector (["Tutorials", "Point", "India"]) −

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

Output

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

The vector elements are:
Ds\Vector Object
(
    [0] => Tutorials
    [1] => Point
    [2] => India
)
The first element of vector: string(9) "Tutorials"

Example 3

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

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

Output

The above program throws the following exception −

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