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

PHP - Ds Sequence::first() Function



The PHPDs\Sequence::first()function is used to retrieve the first value in a sequence. If the current sequence is empty ([]), this function will throw an "UnderflowException".

The PHP Ds\Sequence class provides another function named get(), which retrieves the element at a specific index. If the index is 0, it always returns the first value in a sequence.

Syntax

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

abstract public Ds\Sequence::first(): mixed

Parameters

This function does not accept any parameter.

Return value

This function returns the first value in a sequence.

Example 1

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

<?php
   $seq = new \Ds\Vector([1, 2, 3, 4, 5]);
   echo "The sequence elements are: \n";
   print_r($seq);
   echo "The first value is sequence is: ";
   print_r($seq->first());
?>

Output

The above program produces the following output −

The sequence elements are:
Ds\Vector Object
(
    [0] => 1
    [1] => 2
    [2] => 3
    [3] => 4
    [4] => 5
)
The first value is sequence is: 1

Example 2

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

<?php
   $seq = new \Ds\Vector(["Tutorials", "Point", "India"]);
   echo "The sequence elements are: \n";
   print_r($seq);
   echo "The first value is sequence is: ";
   print_r($seq->first());
?>

Output

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

The sequence elements are:
Ds\Vector Object
(
    [0] => 1
    [1] => 2
    [2] => 3
    [3] => 4
    [4] => 5
)
The first value is sequence is: 1

Example 3

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

<?php
   $seq = new \Ds\Vector([]);
   echo "The sequence elements are: \n";
   print_r($seq);
   echo "The first value is sequence is: ";
   print_r($seq->first());
?>

Output

Once the above program is executed, it throws the following exception −

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