PHP - Ds Map::put() 函式



PHP 的Ds\Map::put()函式用於將鍵與值關聯。將鍵與值關聯涉及到對映或連結特定的鍵到特定的值。

如果該鍵已存在關聯,則現有值將被新值替換。

語法

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

public void Ds\Map::put( mixed $key , mixed $value )

引數

此函式接受兩個名為“key”和“value”的引數,如下所述:

  • key - 要關聯值的鍵。
  • value - 需要與鍵關聯的值。

返回值

此函式不返回值。

示例 1

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

<?php  
   $map = new \Ds\Map();
   echo "The map elements before using put() function: \n";
   print_r($map);
   $k1 = 1;
   $val1 = 10;
   $k2 = 2; 
   $val2 = 20;
   echo "The key1 and key2 are: ".$k1.", ".$k2;
   echo "\nThe values are: ".$val1.", ".$val2;
   #using put() function
   $map->put("1", "10");
   $map->put("2", "20");
   echo "\nThe map elements after using put() function: \n";
   print_r($map);
?>  

輸出

以上程式顯示以下輸出:

The map elements before using put() function:
Ds\Map Object
(
)
The key1 and key2 are: 1, 2
The values are: 10, 20
The map elements after using put() function:
Ds\Map Object
(
    [0] => Ds\Pair Object
        (
            [key] => 1
            [value] => 10
        )

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

)

示例 2

以下是PHP Ds\Map::put()函式的另一個示例。我們使用此函式將鍵“a”與值“Tutorials”關聯:

<?php  
   $map = new \Ds\Map(["b"=>"Point", "c"=>"India"]);
   echo "The map elements before using put() function: \n";
   print_r($map);
   $k = "a";
   $val = "Tutorials";
   echo "The key and value are: ".$k.", ".$val;
   #using put() function
   $map->put($k, $val);
   echo "\nThe map elements after using put() function: \n";
   print_r($map);
?>

輸出

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

The map elements before using put() function:
Ds\Map Object
(
    [0] => Ds\Pair Object
        (
            [key] => b
            [value] => Point
        )

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

)
The key and value are: a, Tutorials
The map elements after using put() function:
Ds\Map Object
(
    [0] => Ds\Pair Object
        (
            [key] => b
            [value] => Point
        )

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

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

)
php_function_reference.htm
廣告