Home > OS >  is there a way to write the code shorther?
is there a way to write the code shorther?

Time:01-17

im trying to make a calculator for school, and this is my code. is it possible to write it shorter? i feel like i can make this even better. Also im new to php and trying to learn and write it clean.

<html>
<h1>Kortingsprijs berekenen</h1>

    <form method="post" action="">
        <label>Prijs in Euro's</label>
        <input type="text" name="prijs" value="<?php if (isset($_POST['prijs'])) {echo $_POST['prijs'];} ?>">
        <br>
        <input  type="radio" name="korting" value="20" />20%
        <br>
        <input  type="radio" name="korting" value="30" />30%
        <br>
        <input  type="radio" name="korting" value="40" />40%
        <br>
        <input  type="radio" name="korting" value="50" />50%
        <br><br>
        <input type="submit" name="Berekenen" value="Berekenen"/>
    </form>
</html>
</strike>
<?php
if(isset($_POST['Berekenen'])) {
    $prijs = filter_input(INPUT_POST, 'prijs', FILTER_VALIDATE_FLOAT);
    $korting = filter_input(INPUT_POST, 'korting', FILTER_VALIDATE_INT);

    
    if ($prijs === false) {
        $bericht = " Vul een prijs in euro's in! ";
    } else {
        if (is_null($korting)) {
            $bericht = "Vul een Korting in!";
        }else{
            switch ($korting){
            case 20:
            $bericht = "Dit is de prijs met 20% korting: € "  . number_format((float)$prijs * 0.8, 2, '.', '') ;
            break;
            case 30:
            $bericht = "Dit is de prijs met 30% korting: € " . number_format((float)$prijs * 0.7, 2, '.', '') ;
            break;
            case 40:
            $bericht = "Dit is de prijs met 40% korting: € " . number_format((float)$prijs * 0.6, 2, '.', '') ;
            break;
            case 50:
            $bericht = "Dit is de prijs met 50% korting: € " . number_format((float)$prijs * 0.5, 2, '.', '') ;
            break;
            }


        }
    }
}else{
    $bericht =" Je hebt niks ingevuld!";
}
?>

<?php echo $bericht;?>

CodePudding user response:

Assuming that $korting should also give a correct output when it is not 20,30,40 or 50, but -- for example -- 25 (even though it is not available in your HTML form), just make the formula generic. And, as your code is focused on producing a value for $bericht, you could use the ternary conditional operator:

$prijs = filter_input(INPUT_POST, 'prijs', FILTER_VALIDATE_FLOAT);
$korting = filter_input(INPUT_POST, 'korting', FILTER_VALIDATE_INT);
$bericht = !isset($_POST['Berekenen']) ? "Je hebt niks ingevuld!"
         : ($prijs === false  ? "Vul een prijs in euro's in! "
           : (is_null($korting) ? "Vul een Korting in!"
             : "Dit is de prijs met $korting% korting: € " .
               number_format((float)$prijs * (1 - $korting / 100.0), 2, '.', '')
             )
           );
  •  Tags:  
  • Related