PHP newbie here. I've created a function that increases prices based on their price range:
function update_price ( $price) {
If (isset($price) ) {
if ($price < 60 ) {
return $price + 40;
}
elseif ($price >= 60 && $price < 100) {
return $price + 60;
}
elseif ($price >= 100 && $price < 200) {
return $price + 70;
}
elseif ($price >= 200 && $price < 300) {
return $price + 80;
}
elseif ($price >= 300 && $price < 450) {
return $price + 90;
}
elseif ($price >= 450) {
return $price + ($price * .2);
}
}
}
The function is called when I import a CSV file. Works great, except for the last part of the function. I'm trying to raise the price of those qualifying products by 20%, so I'm taking $price and adding ($price * .2). But a product that was $628.74 is coming out as $754,888.00 instead of $754.88.
What did I do wrong?
It's OK that PHP returns 754.488, it's the same value returned by a calculator: 628.74÷5+628.74=754.488
Here you would need to round the precision to 2 decimal numbers, this can be done with the round() function.
Also, I would write your function like this:
function update_price($price) {
if((!$price) || (!is_numeric($price)) || ($price <= 0)) // initial price is not valid
return -1;
if($price >= 450) return $price+round($price/5, 2, PHP_ROUND_HALF_DOWN);
if($price >= 300) return $price+90;
if($price >= 200) return $price+80;
if($price >= 100) return $price+70;
if($price >= 60) return $price+60;
return $price+40;
}