Hi there !
Here’s a little exercise I’ve got to do for my php class that just started so it’s very basic, sorry. I was just hoping you could point me out to some improvements that I could implement, where my logic is faulty or where I could’ve coded in a more practical (or beautiful ^^) way
<?php
var_dump($_POST);
$bootypeLoc= MrPropre($_POST['typeloc']??"");
$intAdulte= MrPropre($_POST['nbAdultes']??"");
$intEnfants= MrPropre($_POST['nbEnfants']??"");
$boodemiAdulte= MrPropre($_POST['demipensionadulte']??"");
$boodemiEnfants= MrPropre($_POST['demipensionenfants']??"");
$intAnnul= MrPropre($_POST['intAnnul']??"");
$intPercent= MrPropre($_POST['intPercent']??"");
$intCostAdulte = ssMult($intAdulte, $boodemiAdulte);
$intCostEnfants = ssMult($intEnfants, $boodemiEnfants);
$intSsTotal = ssAdd($bootypeLoc, $intAnnul, $intCostAdulte, $intCostEnfants);
$intRemise = getPercentOfNumber($intSsTotal, $intPercent);
$intTotal= ssAdd($intSsTotal, -$intRemise);
// sanitize and validate int_var
function MrPropre($data){
if(isset($_POST['valider'])){
$error = "";
$data = filter_var($data, FILTER_SANITIZE_NUMBER_INT);
if (filter_var($data, FILTER_VALIDATE_INT) === 0 || !filter_var($data, FILTER_VALIDATE_INT) === false){
$error = false;
return $data;
}
else{
$error = true;
echo '<script>alert("Veuillez ne rentrer que des chiffres et remplir tous les champs svp") </script>';
$data="";
}
}
}
// splat_Add_func
function ssAdd(...$costs){
if(isset($_POST['valider'])){
$sum = 0;
foreach ($costs as $n){
$sum += $n;
}
return $sum;
}
}
// Mult_func
function ssMult($cost1, $cost2){
if(isset($_POST['valider'])){
return $cost1 * $cost2;
}
}
// Percent_func
function getPercentOfNumber($number, $percent){
if(isset($_POST['valider'])){
return ($number / 100) * $percent;
}
}
?>
The input and output forms are on the same page as this code, I guess there’s no point in pasting html here. I just echo’d the result variables in the output form, nothing fancy.
The thing which annoys me the most is that isset condition I had to put at the start of each function. They were being executed at page loading and all the mathematical functions were giving me errors because there was no input data.
As a workaround, I prevented them from executing with isset until the submit button is clicked. Although it’s working as it is, it’s certainly not ideal… nor very aesthetic.
I know I don’t have to go through functions to make these simple calculations, but I’m really interested to learn how someone with more experience would do this differently while keeping the functions
Thanks in advance !