Add variable value with foreach

0

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

$grupo = selectContas();

I would like to add these two values and save them to 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)
    
asked by anonymous 30.01.2018 / 18:06

2 answers

1

You can do the following: Setting 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; ?> 
    
30.01.2018 / 18:18
0
  

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

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

    }
} ?>
    
31.01.2018 / 18:14