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

PHP - Ds Deque::first() Functions



The PHPDs\Deque::first()function is used to retrieve the value of the first element in the current deque. The Ds\Deque class provides another function named get(), which is used to retrieve an element at the given index, and if the index is 0, it will return the first element.

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

Syntax

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

public Ds\Deque::first(): mixed

Parameters

This function does not accept any parameter.

Return value

This function returns the first element in the deque.

Example 1

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

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

Output

The above program displays the first element as '1' −

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

Example 2

Following is another example of thePHP Ds\Deque::first()function. We use this function to retrieve the first value 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 first element of a deque is: ";
   print_r($deque->first());
?>

Output

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

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

Example 3

If the current deque is empty ([]), the first() function will throw an "UnderflowException" as follows:

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

Output

On executing the above program, it throws an "UnderflowException" as:

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