Home > OS >  PHP sum values from multidimensional array with using a for loop
PHP sum values from multidimensional array with using a for loop

Time:12-18

I have a multidimensional array that looks like this..

$array = array (
    'section1' => array (
        'value'  => 465,
        'value2' => 744
    ),
    'section2' => array (
        'value'  => 6544,
        'value2' => 565
    ),
    'section5' => array (
        'value'  => 345,
        'value2' => 7465
    )
);

I want to add all of the value2 together. I know I can do it with a for loop but is there a way to do it without doing this?

Could I use array_sum in combination with array_column to do this? The number of sections and the section name changes so I am not sure how to cater for this.

CodePudding user response:

Use array_map to extract the required key's value, and then use array_sum.

$a = array (
    'section1' => array (
        'value'  => 465,
        'value2' => 744
    ),
    'section2' => array (
        'value'  => 6544,
        'value2' => 565
    ),
    'section5' => array (
        'value'  => 345,
        'value2' => 7465
    )
);

echo array_sum(array_map('v',$a));

function v($v) {return $v['value2'];}

Teh Playground!

CodePudding user response:

array_reduce variant:

$a = array (
    'section1' => array (
        'value'  => 465,
        'value2' => 744
    ),
    'section2' => array (
        'value'  => 6544,
        'value2' => 565
    ),
    'section5' => array (
        'value'  => 345,
        'value2' => 7465
    )
);

print_r($a);

echo array_reduce($a, function($c, $s) { return $c   $s['value2']; }, 0);

// shorter with arrow functions
echo array_reduce($a, fn($c, $s) => $c   $s['value2'], 0);
  •  Tags:  
  • php
  • Related