saltcracker
saltcracker

Reputation: 321

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:

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

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?

Upvotes: 1

Views: 70

Answers (2)

RomanPerekhrest
RomanPerekhrest

Reputation: 92854

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>";

Upvotes: 2

Robert Calove
Robert Calove

Reputation: 449

To remove the last character of a string, you would just call:

substr(0, strlen($string) - 1);

In order to get a total, you need to have a variable to hold the total. Then you can just add to it using:

$total += $price;

Where $price corresponds to the price in your mapping.

Upvotes: 3

Related Questions