Home How to get total sum of every 10 record using php
Reply: 2

How to get total sum of every 10 record using php

Haidhar Husin
1#
Haidhar Husin Published in 2018-01-11 09:41:53Z

for example:

10
10
10
10
10
10
10
10
10
10
10
9

OUTPUT

10
10
10
10
10
10
10
10
10
10
`-----
100

next loop

10
9
`---
19

RamRaider
2#
RamRaider Reply to 2018-01-11 09:56:17Z

It's very simple to do using array_chunk and array_sum

$arr=array(
    10,10,9,10,8,10,7,10,15,10,12,11,10,9,5,21,25,10,15,14,18,12,0,1,2,
    13,18,18,18,12,0,1,2,4,5,25,10,7,10,15,10,12,11,10,9,5,21,25,10,15,
    14,13,18,18,18,12,0,1,2,4,5,25,10,7,10,15,10,12,11,10,9,5,21,25,10,
    15,14,13,18,18,4,5,25,18,12,0,1,2,4,5,25,10,7,10,9,10,8,10,7,10,15
);
$size=10;

foreach( array_chunk( $arr, $size ) as $chunk ){
    printf('%d<br />', array_sum( $chunk ) );
}
Andreas
3#
Andreas Reply to 2018-01-11 10:29:32Z

You can use array_sum and array_splice.

Array_splice cuts out part of the input array and array_sum sums the part.

$arr = range(1,100); // your array
$size = 10;

for($i=0; $i<count($arr)/$size;){
    echo array_sum(array_splice($arr,0,$size)) ."\n";
}

https://3v4l.org/8u00c

Edit; now that I think about it, you don't need the /$size in the loop.
The loop works just as good with:

for($i=0; $i<count($arr);){
    echo array_sum(array_splice($arr,0,$size)) ."\n";
}

Because as long as there is values in $arr it will keep looping and suming values.

You need to login account before you can post.

About| Privacy statement| Terms of Service| Advertising| Contact us| Help| Sitemap|
Processed in 0.316064 second(s) , Gzip On .

© 2016 Powered by mzan.com design MATCHINFO