Sum variables value with foreach

Asked

Viewed 4,281 times

1

I have a variable that performs a select function, returning from the database two values:

$grupo = selectContas();

I would like to add these two values and store them in a variable, but only the value of the last record is being saved.

<?php
    foreach($grupo as $contas){
        $valortotal = '';
        $valortotal = $valortotal + $contas["valor"];
    }
?>

<?=$valortotal?> (Aqui mostra apenas o último valor do registro)

2 answers

4


You can do it as follows: Set the variable to 0, initially later, you do the auto sum, using +=.

<?php
    $valortotal = 0;
    foreach($grupo as $contas){
        $valortotal += $contas["valor"];
    }
?>

Total: <?php echo $valortotal; ?> 
  • It worked, but I was curious because I can’t do it this way: $total value = $total value + $accounts["value"] ? In theory it wouldn’t be the same thing?

  • No, because then he would be adding up values doubly. If it worked, please give an acceptance in my answer. : ) If necessary, post!

0

$valortotal = 0;
foreach($grupo as $contas){

    if(is_numeric($contas)){
        $valortotal = $valortotal + intval($contas["valor"]);

    }
} ?>

Browser other questions tagged

You are not signed in. Login or sign up in order to post.