Working with Prices in PHP

PHP Tutorials

Take an array of numbers, strip out the dollar sign and format them correctly.

This is useful when you are given prices as varchar or text with the dollar sign already included in the field. We’re going to start with an array of numbers, in this case we’ll use the array(‘$1256.45′,’$5564.75′,’$7895.33’).

Here is the foreach loop running:

Start with $1256.45
Strip the $ – 1256.45
Cleaned and formatted number with the dollar sign added back in as a character – $1,256.45

Start with $5564.75
Strip the $ – 5564.75
Cleaned and formatted number with the dollar sign added back in as a character – $5,564.75

Start with $7895.33
Strip the $ – 7895.33
Cleaned and formatted number with the dollar sign added back in as a character – $7,895.33

Here’s the code that performs the task above:

{code type=php}

$number_array = array(‘$1256.45′,’$5564.75′,’$7895.33’);
foreach ($number_array as $number) {
echo “Start with $number
“;
$number = str_replace(‘$’,”,$number);
echo “Strip the $ – $number
“;
$formatted_number = number_format($number, 2, ‘.’,’,’);
echo “Cleaned and formatted number with the dollar sign added back in – $$formatted_number

“;
}
?>

{/code}

Simple Percent off a Price Using PHP and Simple Math

The next thing we’ll do is take our newly formatted numbers and perform a simple calculation to get a percentage off.

We will use the price 1234.67 as our starting price and 45% off as the discount rate.

Here is the foreach loop running:

starting price is $1234.67
45% off of $1234.67 = $555.60
$1234.67 – $555.60 will equal $679.07 – the final sale price

{code type=php} $price = 1234.67;
$percent_off = .45;
echo “starting price is $$price
“;
$money_off = $price * $percent_off;
$money_off = number_format($money_off, 2, ‘.’,’,’);
echo “45% off of $$price = $$money_off
“;

$sale_price = $price – $money_off;
$sale_price = number_format($sale_price, 2, ‘.’,’,’);
echo “$$price – $$money_off will equal $$sale_price – the final sale price”;

?>

{/code}

What's the Buzz?

Andy is a true professional who is one of the most capable people I have ever worked with. His enthusiasm for his job is impressive and his ability to adapt and evolve to a new task is incredible. He is one of those rare people who you can tell where you want to get to and he can engineer the path there for you and give you extra choices along the way. His ability to learn new skills, willingness to continue to grow and expand is astounding. He’s also very skilled at what he does now and has a great eye for design and usability, blending form and function with class. And he’s fun to spend time with.

- Claire Devereux Thompson
Sterling Advertising