PHP - Ds Sequence::first() 函式



PHP 的 Ds\Sequence::first() 函式用於檢索序列中的第一個值。如果當前序列為空 ([]),此函式將丟擲“UnderflowException”異常。

PHP Ds\Sequence 類提供另一個名為 get() 的函式,該函式檢索特定索引處的元素。如果索引為 0,它始終返回序列中的 第一個值。

語法

以下是 PHP Ds\Sequence::first() 函式的語法:

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

引數

此函式不接受任何引數。

返回值

此函式返回序列中的第一個值。

示例 1

以下是 PHP Ds\Sequence::first() 函式的基本示例:

<?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());
?>

輸出

上述程式產生以下輸出:

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

示例 2

以下是 PHP Ds\Sequence::first() 函式的另一個示例。我們使用此函式來檢索此序列 (["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());
?>

輸出

執行上述程式後,將顯示以下輸出:

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

示例 3

如果當前序列為空 ([]),此函式將丟擲“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());
?>

輸出

執行上述程式後,它將丟擲以下異常:

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
廣告