Jump to content

calculate discounts on the fly


phpnew

Recommended Posts

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
 

Link to comment
Share on other sites

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.

Link to comment
Share on other sites

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

 

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.