How to sum PHP values inside a "for" to bring the total

1

I have the following schedule, which brings the price of each selected item:

for($x=1;$x<=4;$x++){
    if($_POST['p'.$x] != '0'){
    $sql = "SELECT produto, preco FROM produtos WHERE p = '".$px."'";
    $result = $db->query($sql);
    $obj = mysqli_fetch_object($result);
    $preco = $obj->preco;
    echo $preco.'<br/>';
    }
}

It brings for example:

10
11
15

I wanted you to bring it all together into another variable to bring it:

10
11
15
36

How can I do this?

    
asked by anonymous 29.08.2017 / 14:10

1 answer

4

Simple, declare a variable out of for, and sum it within the for.

Following your code:

$total = 0;

for($x=1;$x<=4;$x++){
    if($_POST['p'.$x] != '0'){
    $sql = "SELECT produto, preco FROM produtos WHERE p = '".$px."'";
    $result = $db->query($sql);
    $obj = mysqli_fetch_object($result);
    $preco = $obj->preco;

    $total += $preco;

    echo $preco.'<br/>';
    }
}
    
29.08.2017 / 14:16