Iswadi Iswadi - 5 months ago 13
PHP Question

how to sum array using php?

how to add fare if the data generated like this ? so that there can be the total number of tariff
how to add fare if the data generated like this ? so that there can be the total number of tariff



Array
(
[3] => Array
(

[TARIFF] => 0

)

[4] => Array
(

[TARIFF] => 0

)

[2] => Array
(

[TARIFF] => 29500

)

[0] => Array
(

[TARIFF] => 20500

)

[1] => Array
(

[TARIFF] => 14500

)

)




Answer

There are multiple ways to sum your array:

  • You can use array_sum() in combination with array_column()
  • You can use a foreach
  • You can use array_map()
  • You can use array_reduce() - (Mark Baker)

array_sum() and array_column()

$total = array_sum(array_column($array, 'TARIFF'));

foreach

$total = 0;
foreach ($array as $value) {
    $total += $value['TARIFF'];
}

array_map()

$count = array_sum(array_map(function ($value) {
    return $value['TARIFF'];
}, $array));

array_reduce() - Thanks to Mark Baker

array_reduce($array, function($runningTotal, $value) {
    $runningTotal += $value['TARIFF'];
    return $runningTotal;
}, 0);

Sources:

Comments