PHP - Ds Map::sum() 函式



PHP 的 Ds\Map::sum() 函式用於檢索對映中所有值的總和。根據當前對映中的值,它可以是浮點型或整型。

在計算對映中所有值的總和時,陣列和物件被認為等於

語法

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

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

引數

此函式不接受任何引數。

返回值

此函式返回對映中所有值的總和。

示例 1

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

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

輸出

執行上述程式後,它將顯示對映值的總和為:

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

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

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

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

)
The sum of the map values: 10

示例 2

以下是 PHP Ds\Map::sum() 函式的另一個示例。我們使用此函式來檢索此對映 ([1 => 10.5, 2 => 20.0, 3 => 30.5]) 的所有值的總和:

<?php 
   $map = new \Ds\Map([1 => 10.5, 2 => 20.0, 3 => 30.5]);
   echo "The map values are: \n";
   foreach($map as $key=>$value){
	   echo $key." = ".$value."\n";
   }
   echo "The sum of the map values: ";
   print_r($map->sum());   
?>

輸出

上述程式產生以下輸出:

The map values are:
1 = 10.5
2 = 20
3 = 30.5
The sum of the map values: 61

示例 3

對映中字元或字串值的總和將等於0

<?php 
   $map = new \Ds\Map(['a', 'b', 'c']);
   echo "The map values are: \n";
   foreach($map as $key=>$value){
	   echo $key." = ".$value."\n";
   }
   echo "The sum of the map values: ";
   print_r($map->sum());   
?>

輸出

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

The map values are:
0 = a
1 = b
2 = c
The sum of the map values: 0
php_function_reference.htm
廣告