phpnew Posted September 24, 2018 Share Posted September 24, 2018 I have products that are offered at discounted prices. A web page shows a full price, discounted price, and the value of a discount. I would do it in this way (example shows a single product): $price1f = "59.99"; $price1 = "39.99"; $price1d = $price1f - $price1; Fair enough... "f" is for a full price, nothing after "1" is current discounted price, and "d" is for a value of the discount. Now, is it possible to evade the "d" part, and use a function based on calling on existing full or discounted price variable, and calculating the discount? So, in HTML page I do this: <p><?php echo showDiscount($price1);?></p> This showDiscount() is supposed to figure that the discount is "$price1f - $price1" based on that number "1" that determines a single product. So, if we call on $price23, we know that the value of the discount is "$price23f - $price23" I tried with getting a variable, then trimming or appending "f" then with eval() to create a variable from a string, but no success. I probably took a wrong path. If I already have full and discount price stored, hot to call on two of them to calculate a discount? Thanks Quote Link to comment Share on other sites More sharing options...
requinix Posted September 24, 2018 Share Posted September 24, 2018 Not like that, no. In fact you need to abandon the approach entirely and forget you thought of it in the first place. You shouldn't have so many variables for these things. You should have a Product thing, which knows its regular price. You should have... something that knows about the current price. If you know the product and the offered price then you can get the discount. Quote Link to comment Share on other sites More sharing options...
Barand Posted September 24, 2018 Share Posted September 24, 2018 At the very least, use an array instead of all those variables $products = [ 1 => ['F' => 59.99, 'D' => 39.99 ], 2 => ['F' => 39.99, 'D' => 29.99 ], 3 => ['F' => 99.99, 'D' => 79.99 ] ]; function discount($prod_no, &$products) { $prod = $products[$prod_no]; return sprintf('%0.2f', $prod['F'] - $prod['D']); } echo discount(2, $products); //--> 10.00 Quote Link to comment Share on other sites More sharing options...
phpnew Posted September 24, 2018 Author Share Posted September 24, 2018 Thanks very much for the array solution. That's the way to go at this time. Thanks again. Quote Link to comment Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.