mardi 19 octobre 2021

How to calculate shipping cost by weight using PHP?

I have to calculate the shipping cost for clothing, which has weight.

Price for the delivery is PKR 200 for up to 1.0 KG and then PKR 50 for each additional 0.5 KG.

Max weight of the delivery is 5 kg. I could do PHP if else but I would like to come out with some elegant solution. Any help will be deeply appreciated.

$weight = 1.5;
$default_weight = 1.0;
$shipping = 200;
$additional_per_half_kg = 0.5;
$additional_charge_per_half_kg = 100;
$max_weight_kg = 5.0;
if($weight <= $default_weight){
    echo $shipping;
}else if($weight <= $max_weight_kg){
    $fee = $shipping+$additional_charge_per_half_kg*(($weight-0.5)/($additional_per_half_kg));
    echo $fee;
}else{
    echo "Overweight";
}

Example

0.1 to 1.0 KG = PKR 200

1.1 KG to 1.5 KG = 300

1.6 KG to 2.0 KG = 400

2.1 KG to 2.5 KG = 500

Aucun commentaire:

Enregistrer un commentaire