saltcracker saltcracker - 2 years ago 59
PHP Question

How do I sum this

I'm making a simple submit form which sends the data to another PHP file and displays the data. I almost just started learning PHP, so please bear with me.

The form has several types of input, but the problem I'm having is the checkboxes:

<input type="checkbox" name="fyll[]" value="Bacon">
<input type="checkbox" name="fyll[]" value="Ananas">
<input type="checkbox" name="fyll[]" value="Ekstra ost">
Ekstra ost<br>
<input type="checkbox" name="fyll[]" value="Skinke">
<input type="checkbox" name="fyll[]" value="Sopp">

Which sends data to this file:

$fyllPriser = array("Bacon" => 25,
"Ananas" => 5,
"Ekstra ost" => 10,
"Skinke" => 10,
"Sopp" => 15

$fyll = $_POST['fyll'];
$fyllLenght = count($fyll);

for ($i = 0; $i < $fyllLenght; $i++){
echo "<span>";
echo $fyll[$i], ", </span>"; //<----- Displays all checked checkboxes
$fyllPris = $fyllPriser[$fyll[$i]]; //< Prices for each checked checkbox
echo $fyllPris;

The array $fyllPriser contains the prices for each item with the same key as the value name of the inputs.
Everything is displayed, but I want to sum all the prices for each checked checkbox.

Right now it is displayed like this:
Bacon, Ananas,

I want to remove the comma behind the last item, how can I do that?

And if I echo the prices too, I get this:
Bacon, 25Ananas, 5

In this case, I want to add 25+5=30 and put the sum into a variable so I can use it later to create a "total sum" or something. How do I do that?

Answer Source

Here is the solution:

        $fyll = $_POST['fyll'];
        $fylls = [];
        $totalPrice = 0;

        foreach ($fyll as $v){
           $fylls[] = "<span>". $v . "</span>";
           $totalPrice += $fyllPriser[$v];
        echo implode(',', $fylls);
        echo "<span> total price: $totalPrice</span>";
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download