phparray-sum

how to sum element in array base key


i have array like this

[1001] => Array
        (
            [0] => 500
        )

    [1204] => Array
        (
            [0] => 750
        )

    [1202] => Array
        (
            [0] => 0
            [1] => 10000
            [2] => 138456
        )

    [1203] => Array
        (
            [0] => 300
        )



)

i want Sum each element of array in key to new output like this

[1001] => Array
        (
            [0] => 500
        )
[1204] => Array
        (
            [0] => 750
        )
[1202] => Array
        (
            [0] => 148456

        )
[1203] => Array
        (
            [0] => 300
        )





)

Thanks !


Solution

  • You can use array_map to apply array_sum to each of the elements of the array:

    $sum_array = array_map(function ($v) { return array_sum($v); }, $array);
    print_r($sum_array);
    

    Demo on 3v4l.org