• PHP Video Tutorials

PHP - Ds Set first() Function



The PHP Ds\Set::first() function is used to retrieve the first value of the current set. It does not accept any index value to retrieve an element; it simply returns the first element of the set.

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

Syntax

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

public Ds\Set::first(): mixed

Parameters

This function does not accept any parameter.

Return value

This function returns the first value in the set.

Example 1

The following is the basic example of the PHP Ds\Set::first() function.

<?php
   $set = new \Ds\Set([11, 121, 12121, 1212121]);
   echo "The set elements are: \n";
   print_r($set);
   echo "The first element of the set is: ";
   #using first() function
   print_r($set->first());
?>

Output

The above program produces the following output −

The set elements are:
Ds\Set Object
(
    [0] => 11
    [1] => 121
    [2] => 12121
    [3] => 1212121
)
The first element of the set is: 11

Example 2

The following is another example of the PHP Ds\Set::first() function. We use this function to retrieve the first element of this set (["Welcome", "to", "Tutorials", "point"]).

<?php
   $set = new \Ds\Set(["Welcome", "to", "Tutorials", "point"]);
   echo "The set elements are: \n";
   print_r($set);
   echo "The first element of the set is: ";
   print_r($set->first());
?>

Output

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

The set elements are:
Ds\Set Object
(
    [0] => Welcome
    [1] => to
    [2] => Tutorials
    [3] => point
)
The first element of the set is: Welcome

Example 3

If the current set is empty, this function will throw an "UnderflowException" exception.

<?php
   $set = new \Ds\Set([]);
   echo "The set elements are: ";
   print_r($set);
   echo "The first element of the set is: ";
   print_r($set->first());
?>

Output

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

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