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.
2
Answers
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
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
If you’re using PHP 8, this would be elegantly done with
match
: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 simplematch($fee)
wouldn’t work. We needmatch(true)
instead, where, when an expression evaluates as true, the corresponding value will be returned. Note thatmatch
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: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
andswitch
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.