PHP Calculate Percentage

825 Views

In this tutorial I will teach you how to calculate percentage increase and percentage decreased in PHP.

Percentage Decreased
This is the most common and used in many areas such as calculating a sales price.

$price      = 50;// Original cost of item
$sale_price = 30;// New sale price

// We determine the sale difference
$price_diff = $price - $sale_price;

// Next we divide the price_diff by the original price 
$percent_sale = $price_diff / $price;

// Finally we multiply by 100 to get the percentage and format.
$percent_sale = number_format( $percent_sale * 100, 0 ) . '%';

Result: 40%

Percentage Increase
Calculating percentage increase in PHP is similar to the decrease method except in this case we subtract from the new total.

$hours_last_week      = 40;// Hours worked last week
$hours_this_week      = 50;// Hours worked this week

// Get difference in hours worked
$hours_diff = $hours_this_week - $hours_last_week;

// Next we divide the hours_diff by the original hours. 
$hours_diff = $hours_diff / $hours_last_week;

// Finally we multiply by 100 to get the percentage and format.
$hours_diff = number_format( $hours_diff * 100, 0 ) . '%';

Result: 25%

Thats it. Easy examples how to calculate percentage in PHP.

Please Post Your Comments & Reviews

Welcome to Western Studios

We provide professional website and mobile softwares including Joomla, Wordpress and more.