0
I need to sum up the values provided by an array. The array comes from a select in the database.
The array is this way:
Array (
[0] => Array ( [valorPagamento] => 12 )
[1] => Array ( [valorPagamento] => 50 )
[2] => Array ( [valorPagamento] => 10 )
)
I would like to add these figures: 12,50,10
I’ve used the array_sum
in this way:
echo "soma: ".array_sum($total);
The variable $total
that brings back the array, however the result of always 0;
I also tried that function:
$sum = 0;
foreach($total as $key=>$value){
$sum+= $value;
}
echo $sum;
Here, when I use the function fetch
it shows only the first line when using fetchAll
it shows the following error:
Unsupported operand types
My codes are these: paymentContasDAO.php file (only the function I’m using):
function soma(){
try{
$stmt = $this->pdo->prepare("SELECT valorPagamento FROM pagamentocontas");
$stmt->execute();
$consulta = $stmt->fetchAll(PDO::FETCH_ASSOC);
return $consulta;
}catch (PDOException $ex){
echo "ERRO 02: {$ex->getMessage()}";
}
}
php sum file.:
<?php
require_once ("../DAO/pagamentoContasDAO.php");
$dao = new pagamentoContasDAO();
$consulta = $dao->soma();
?>
paymentContas.php:
<?php
require_once ("../Controller/soma.php");
$sum = 0;
foreach($consulta as $key=>$value){
$sum+= $value;
}
echo $sum;
?>
Well, I hope you understand my problem.
You can thank me by giving upvote haha. It’s normal to hit head at the very beginning
– Lucas
All right. Vlw right.
– Julio Cesar