Home > Enterprise >  PHP Calculate fee by price range
PHP Calculate fee by price range

Time:04-09

Is anyone who can help me to create PHP and mysql Code. Here is the condition.

If price range is 1 to 20 USD, it will be show 2 USD. If price range is 21 to 50 USD, it will be show 5 USD. If price range is 51 to 100 USD, it will be show 7 USD.

how to do it with PHP or WordPress php coding.

CodePudding user response:

I don't get the MySQL part here did you want to do this on the database level? or are you looking for both? anyway, in PHP it should be like this

$price = 5;

if($price >= 1 && $price <= 20){
  $price = 2;
}else if($price > 20 && $price <= 50){
  $price = 5;
}else if($price > 50 && $price <= 100){
  $price = 7;
}

Note: you should be careful with the ranges 20.1 is greater than 20 but it is less than 21

I hope it's helpful

CodePudding user response:

If you're using PHP 8, this would be elegantly done with match:

$fee = match(true) {
    $price <= 20 => 2,
    $price <= 50 => 5,
    $price <= 100 => 7,
    default => 0 // free shipping!
};

Since the evaluation ends when a "match arm" matches, we don't need to define the lower range -- as long as our ranges are defined in ascending order. I haven't used $price >= 1 && $price <= 20 => 2 for the first condition, assuming that $0.50 still costs something.

Since we're evaluating for the truth of expressions (true|false), a simple match($fee) wouldn't work. We need match(true) instead, where, when an expression evaluates as true, the corresponding value will be returned. Note that match must be exhaustive, ie. it must have a default condition if none of the conditions match (or you get an error).

On older PHP versions, the more long-winded switch can be used:


switch(true) {
    case ($price >= 1 && $price <= 20):
        $fee = 2;
        break;
    case $price <= 50:
        $fee = 5;
        break;
    case $price <= 100:
        $fee = 7;
        break;
    default: 
        $fee = 0;
        break;
};

While switch doesn't require a default statement, it's a good idea to have a default value for transactions that exceed your ranges. Being nice, I give free shipping for orders > 100.

You can also of course use a series of if/elseif statements, but they become quite clunky if you have more than a small handful of conditions to check. match and switch exist to make cases like this more readable and easier to maintain.

Per @AhmedHassan's notes, your logic has a gap between 20/21, and 50/51. The next step from "less than or equal to 20" has to be "more than 20, less than or equal with 50". Or, if $20 flat already incurs the higher fee, then you should use >= 20 and < 50 for your price range boundaries.

  • Related