PHP - Ds Map::first() 函式



PHP 的 Ds\Map::first() 函式用於檢索對映中的第一對。這對指的是對映元素的鍵和值。此函式返回一個包含對映的第一個鍵值對的陣列。

如果當前對映為空,則此函式會丟擲 UnderflowException 異常,指示沒有元素可檢索。

語法

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

public Ds\Map::first(): Ds\Pair

引數

此函式不接受任何引數。

返回值

此函式返回對映中的第一對。

示例 1

以下程式演示了 PHP Ds\Map::first() 函式的用法:

<?php 
   $map = new \Ds\Map([10, 20, 30, 40]); 
   echo "The map elements are: \n";
   print_r($map);
   echo "The first pair of a map: \n";
   #using the first() function
   print_r($map->first()); 
?>

輸出

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

The map elements are:
Ds\Map Object
(
    [0] => Ds\Pair Object
        (
            [key] => 0
            [value] => 10
        )

    [1] => Ds\Pair Object
        (
            [key] => 1
            [value] => 20
        )

    [2] => Ds\Pair Object
        (
            [key] => 2
            [value] => 30
        )

    [3] => Ds\Pair Object
        (
            [key] => 3
            [value] => 40
        )

)
The first pair of a map:
Ds\Pair Object
(
    [key] => 0
    [value] => 10
)

示例 2

以下是 Ds\Map::first() 函式的另一個示例。我們使用此函式來檢索此對映 (["Tutorials", "Point", "India"]) 的第一對:

<?php 
   $map = new \Ds\Map(["Tutorials", "Point", "India"]); 
   echo "The map elements are: \n";
   print_r($map);
   echo "The first pair of a map: \n";
   #using the first() function
   print_r($map->first()); 
?>

輸出

上述程式生成以下輸出:

The map elements are:
Ds\Map Object
(
    [0] => Ds\Pair Object
        (
            [key] => 0
            [value] => Tutorials
        )

    [1] => Ds\Pair Object
        (
            [key] => 1
            [value] => Point
        )

    [2] => Ds\Pair Object
        (
            [key] => 2
            [value] => India
        )

)
The first pair of a map:
Ds\Pair Object
(
    [key] => 0
    [value] => Tutorials
)

示例 3

如果當前對映為空,則此函式會丟擲 "UnderflowException" 異常。

<?php 
   $map = new \Ds\Map([]); 
   echo "The map elements are: \n";
   print_r($map);
   echo "The first pair of a map: \n";
   #using the first() function
   print_r($map->first()); 
?>

輸出

執行上述程式後,將生成以下輸出:

The map elements are:
Ds\Map Object
(
)
The first pair of a map:
PHP Fatal error:  Uncaught UnderflowException: 
Unexpected empty state in C:\Apache24\htdocs\index.php:7
Stack trace:
#0 C:\Apache24\htdocs\index.php(7): Ds\Map->first()
#1 {main}
  thrown in C:\Apache24\htdocs\index.php on line 7
php_function_reference.htm
廣告