3

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
            
        )

)

3
  • 2
    array_sum(array_column($array, 'TARIFF')); Commented Jun 17, 2016 at 8:29
  • 1
    array_reduce($array, function($runningTotal, $value) { $runningTotal += $value['TARIFF']; return $runningTotal; }, 0); Commented Jun 17, 2016 at 8:32
  • 2
    Or just get your database query to do it for you Commented Jun 17, 2016 at 8:32

2 Answers 2

4

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:

Sign up to request clarification or add additional context in comments.

Comments

1

Use array_sum() along with array_column()

Example

$a = array(
    "a"=>52.2,
    "b"=>13.7,
    "c"=>0.9
);
echo array_sum($a);

In Your case

array_sum(array_column($arrayName, 'TARIFF'));

Links to reffer

  1. array_sum in W3School.com
  2. array_column() in W3School.com

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.