Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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
            
        )

)
like image 981
Iswadi Avatar asked Dec 01 '25 09:12

Iswadi


1 Answers

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:

  • array_sum() - Manual
  • array_column() - Manual
  • foreach - Manual
  • array_map() - Manual
  • array_reduce() - Manual
like image 156
Peter Avatar answered Dec 04 '25 01:12

Peter



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!