1

I have values from database trying to add the next value with the initial value then insert into an array, can somebody help me here, please?

while ($row = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_ASSOC)) {   
        $balance[]  =   (round($row["Balance"], 2))++;;
    }

Scenario:

I have 1,2,3,4,5 values I want to get these values into an array as below:

{1,3,6,10,15}

That is:

{1, (1+2), (1+2+3), (1+2+3+4), (1+2+3+4+5)}

Any one with an idea?

2 Answers 2

1

You would be better off just having a running total and adding this in...

$total = 0;
while ($row = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_ASSOC)) {  
    $total = round($row["Balance"], 2) + $total;
    $balance[]  = $total;
}
Sign up to request clarification or add additional context in comments.

Comments

0

Maybe that:

$a = [1,2,3,4,5];

$b = [];

foreach($a as $c) {
    if(count($b) === 0) {
        $b[] = $c;
    } else {
        $b[] = end($b) + $c;
    }
}

$b is result.

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.