The right to put the array in a loop php?

Good day,

I want to sum the values of cells in a loop.
There is a function:
function get_sum($arr) {
 $sum = 0.00;
 foreach($arr as $elem)
 $sum += $elem;
 return $sum;
}


In a loop, collect the array:
// $values = array(1.12,2.33,5.05,100.24); // Option-1
 $values = array($row['go_rs']); // and Tried array($row['go_rs'] . ''). Option-2
// if you put echo ($row['go_rs'] . ''); in the loop we get: 342.12 1244.24 2352.14 etc.


And display
echo get_sum($values); 
// Variant-1 lists all true = 108.74
// Option-2 only displays the last value in the cycle, ie, not sums.


Ie problem in array formation, supposed to be of this type (n1,n2,n3,n4) If you add array($row['go_rs'] . ',')
there is a problem with the last comma.

Tell me, how to collect the array to output the values ?
June 8th 19 at 17:23
1 answer
June 8th 19 at 17:25
Solution
php.net/manual/ru/function.array-sum.php

<?php
$values = [1.12, 2.33, 5.05, 100.24];

echo array_sum($values);</code-->
br><br> output: 108.74<br><br> PS I do Not much understand about option 2, that is, <code>$row['go_rs']</code>? Show it to <code>var_dump()</code>.<br><br><code>array($row['go_rs'] . ',')</code> is the concatenation of strings. And You as I understand the <code class="php">$row['go_rs']</code> is an array.
,
$values = array($row['go_rs']); // and Tried array($row['go_rs'] . ''). Option-2
// if you put echo ($row['go_rs'] . ''); in the loop we get: 342.12 1244.24 2352.14 etc.

This should withdraw. Option-1 led, for example, that the function works, what to do with option 2 to work? about array_sum know, the error here is in the collection of array, that said, I can't domonate - timmy commented on June 8th 19 at 17:28
I don't see that in this array (array($row['go_rs']);), show its structure, example input, and what they need at the output. - sofia.Maggio commented on June 8th 19 at 17:31
itself $row['go_rs'] is the output lines of the column from the database.
the var dump displays the last value in the cycle array(1) { [0]=> string(6) "322.17" }
Somewhere in the logic wrong. I'm trying to build an array in a loop
foreach($array as $row){
...
 $values = array($row["go_rs"]);
...
}

Understand that the logic is wrong, but where exactly I do not understand. - timmy commented on June 8th 19 at 17:34
I think I understand.

$values = [];

foreach ($array as $row) {
 $values[] = $row['go_rs'];
}

echo array_sum($values);


At each iteration of the loop will append a new element to the array values. - sofia.Maggio commented on June 8th 19 at 17:37
exactly, thank you very much, works OK, understand where the gap in logic allowed. - timmy commented on June 8th 19 at 17:40

Find more questions by tags PHP