Add value of an array

Asked

Viewed 11,884 times

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 $totalthat 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 fetchit shows only the first line when using fetchAllit 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.

2 answers

6


You have a multidimensional array, so array_sum does not work. Its function is almost correct, just add the key valorPagamento:

$sum = 0;
foreach ($total as $key => $value){
    $sum += $value['valorPagamento'];
}
echo $sum;
  • You can thank me by giving upvote haha. It’s normal to hit head at the very beginning

  • All right. Vlw right.

3

I used this method a lot, today has this:

 $total = array_sum ( array_column($itens, 'preco') );

Remembering that the array_column() function appeared in PHP 5.5

Browser other questions tagged

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