PHP - Ds Map::clear() 函式



PHP 的 Ds\Map::clear() 函式用於移除當前對映中的所有值。如果我們呼叫此函式的對映已經為空,則不會影響對映,並且它將保持不變。

呼叫 clear() 函式後,當前對映將為空。您可以使用 isEmpty() 函式驗證這一點,如果對映為空,則該函式返回“true”,否則返回“false”。

語法

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

public Ds\Map::clear(): void

引數

此函式不接受任何引數。

返回值

此函式不返回值。

示例 1

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

<?php 
   $map = new \Ds\Map([1, 2, 3, 4, 5]);
   echo "The map elements are: \n";
   foreach($map as $key=>$value){
   echo "[".$key."]"." = ".$value."\n";
   }
   #using clear() function
   $map->clear(); 
   echo "The map after the clear() function called: \n";
   print_r($map); 
?>

輸出

以上程式輸出如下:

The map elements are:
[0] = 1
[1] = 2
[2] = 3
[3] = 4
[4] = 5
The map after the clear() function called:
Ds\Map Object
(
)

示例 2

以下是 PHP Ds\Map::clear() 函式的另一個示例。我們使用此函式清除此對映的所有值(["Tutorials", "Point", "India"]):

<?php 
   $map = new \Ds\Map(["Tutorials", "Point", "India"]);
   echo "The map elements are: \n";
   foreach($map as $key=>$value){
   echo "[".$key."]"." = ".$value."\n";
   }
   #using clear() function
   $map->clear(); 
   echo "The map after the clear() function called: \n";
   print_r($map); 
?>

輸出

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

The map elements are:
[0] = Tutorials
[1] = Point
[2] = India
The map after the clear() function called:
Ds\Map Object
(
)

示例 3

如果我們呼叫的當前對映已經為空,則 clear() 函式不會影響對映,並且對映將保持不變:

<?php 
   $map = new \Ds\Map([]);
   echo "The map elements are: \n";
   foreach($map as $key=>$value){
   echo "[".$key."]"." = ".$value."\n";
   }
   #using clear() function
   $map->clear(); 
   echo "The map after the clear() function called: \n";
   print_r($map); 
?>

輸出

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

The map elements are:
The map after the clear() function called:
Ds\Map Object
(
)
php_function_reference.htm
廣告