PHP - Ds Set::sum() 函式



PHP 的 Ds\Set::sum() 函式用於檢索集合中所有值的總和。根據當前集合中的值,它可以是 floatint 型別。

在計算集合中所有值的總和時,陣列和物件被視為零。

語法

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

public Ds\Set::sum(): int|float

引數

此函式不接受任何引數。

返回值

此函式返回當前集合中所有值的總和。

示例 1

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

<?php
   $set = new \Ds\Set ([1, 2, 3, 4, 5]); 
   echo "The set values are: \n";
   print_r($set);
   echo("The sum of all values: ");
   #using sum() function   
   print_r($set->sum());  
?>

輸出

以上程式產生以下輸出:

The set values are:
Ds\Set Object
(
    [0] => 1
    [1] => 2
    [2] => 3
    [3] => 4
    [4] => 5
)
The sum of all values: 15

示例 2

以下是 PHP Ds\Set::sum() 函式的另一個示例。我們使用此函式來檢索此集合 ([10.25, 20.35, 30.15, 50.25]) 中所有值的總和:

<?php
   $set = new \Ds\Set ([10.25, 20.35, 30.15, 50.25]); 
   echo "The set values are: \n";
   print_r($set);
   echo("The sum of all values: ");
   #using sum() function   
   print_r($set->sum());  
?>

輸出

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

The set values are:
Ds\Set Object
(
    [0] => 10.25
    [1] => 20.35
    [2] => 30.15
    [3] => 50.25
)
The sum of all values: 111
php_function_reference.htm
廣告