lacyeex
lacyeex

Reputation: 175

Sum each row of a multidimensional array

I want to sum each row of a multidimensional array :

$number = array
(
    array(0.3,0.67, 0.3),
    array(0.3,0.5,1),
    array(0.67,0.67,0.3),
    array(1,0.3,0.5)
);

The result what i want is like this :

row1 = 1.27
row2 = 1.8
row3 = 1.64
row4 = 1.8

I already tried this code :

for($i = 0; $i < 4; $i++) {
    for($j = 0; $j < 5; $j++) {
        $sumresult[] = array_sum($number[$i][$j]);
    }
}

But it appear an error like this :

Warning: array_sum() expects parameter 1 to be array, double given in xxxx

Upvotes: 0

Views: 744

Answers (3)

AbraCadaver
AbraCadaver

Reputation: 79024

It's easier to just map the array_sum() function to the array to sum the inner arrays:

$sumresult = array_map('array_sum', $number);

Upvotes: 0

CarlosCarucce
CarlosCarucce

Reputation: 3569

its because you are passing an value instead of the array containing it.

One correct solution would be:

$sumResult = array();

foreach($number as $values){
    $sumResult []= array_sum($values);
}

print_r($sumResult);

Should do the trick ;)

Upvotes: 0

Thamilhan
Thamilhan

Reputation: 13323

array_sum needs array not values. Do like this:

for($i = 0; $i < 4; $i++) {
    $sumresult[] = array_sum($number[$i]);
}

Upvotes: 2

Related Questions