Variable Visions

Calculate percentages with PHP arrays, round, a foreach loop

Published Tue. Jan. 22, 2013

So, my Monday morning project at work was to create an html email template offering 10% off certain products. I copied my email blast html template and went to work designing. Now, with NetSuite I can create a promotional code and assign it a discount value during the checkout process. But since I’m creating an html email, I need to hard code the dollar values. The powers that be wanted to show before (with red cross through) and after discount prices. I could have easily done the math via a calculator and just hardcoded the discounts, but I wanted to try some php scripting to see if I could not only calculate percentage discounts, but also loop through all the amounts, in an array, and give me a nice list that I can then hard code back into my email template. Since I set up my server’s .htaccess file to allow html pages to process php (AddType application/x-httpd-php .html) I used the same file. Of course, I’ll remove the server side code before I blast with NetSuite.

<?php

$originalpricearray = array('238.86', '125.24', '69.00', '191.10', '240.00', '251.79', '1020.02', '1097.00');

foreach ($originalpricearray as $originalpriceitem) {

                $saleprice = $originalpriceitem - round($originalpriceitem * .10, 2);

                echo "SALE PRICE: <strong>$$saleprice</strong> <br />

                ORIGINAL PRICE: <strong style=\"text-decoration:line-through; color: red;\">$$originalpriceitem</strong><br /><br />";          

}

?>

 

 

 

 

$originalpricearray = array('238.86', '125.24', '69.00', '191.10', '240.00', '251.79', '1020.02', '1097.00');

foreach ($originalpricearray as $originalpriceitem) {

                $saleprice = $originalpriceitem - round($originalpriceitem * .10, 2);

                echo "SALE PRICE: <strong>$$saleprice</strong> <br />

                ORIGINAL PRICE: <strong style=\"text-decoration:line-through; color: red;\">$$originalpriceitem</strong><br /><br />";          

}

 

Next time I will trying a user input form, as well as showing  10, 20, 30 etc. percentages off each array value within the same forech loop.

 

http://www.variablevisions.com/articles/Process-PHP-on-an-HTML-page

http://www.variablevisions.com/articles/How-to-set-up-a-NetSuite-email-campaign

 

Keywords:PHP arrays, round, foreach loop