PHP - Ds Set::last() 函式



PHP 的Ds\Set::last()函式用於檢索當前集合的最後一個值。它不接受任何索引值來檢索元素;它只是返回集合的最後一個元素。

如果當前集合為空,此函式將丟擲“UnderflowException”異常。

語法

以下是 PHP Ds\Set::last() 函式的語法:

public Ds\Set::last(): mixed

引數

此函式不接受任何引數。

返回值

此函式返回集合中的最後一個值。

示例 1

以下程式演示了 PHP Ds\Set::last() 函式的用法。

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

輸出

上述程式顯示此集合的最後一個值是“1212121”。

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

示例 2

以下是 PHP Ds\Set::last() 函式的另一個示例。我們使用此函式來檢索此集合 (["Welcome", "to", "Tutorials", "point"]) 的最後一個元素。

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

輸出

上述程式返回最後一個元素為“point”。

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

示例 3

如果當前集合為空last() 函式將丟擲“UnderflowException”異常。

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

輸出

執行上述程式時,將丟擲以下錯誤:

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