Skip to content

Instantly share code, notes, and snippets.

@giltotherescue
Created February 24, 2012 15:19
Show Gist options
  • Star 6 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save giltotherescue/1901577 to your computer and use it in GitHub Desktop.
Save giltotherescue/1901577 to your computer and use it in GitHub Desktop.
Calculate Percentage Change
<?
/**
Calculates the percentage change between two numbers.
Useful for showing how much traffic has changed from one time period to the next.
*/
$percentChange = function ($cur, $prev) {
if ($cur == 0) {
if ($prev == 0) {
return array('diff' => 0, 'trend' => '');
}
return array('diff' => -($prev * 100), 'trend' => 'down_arrow');
}
if ($prev == 0) {
return array('diff' => $cur * 100, 'trend' => 'up_arrow');
}
$difference = ($cur - $prev) / $prev * 100;
$trend = '';
if ($cur > $prev) {
$trend = 'up_arrow';
} else if ($cur < $prev) {
$trend = 'down_arrow';
}
return array('diff' => round($difference, 0), 'trend' => $trend);
};
### TESTS ###
# Decreasing
print_r($percentChange(2, 7)); print "\n";
# Increasing
print_r($percentChange(7, 3)); print "\n";
# Increasing
print_r($percentChange(7, 0)); print "\n";
# Decreasing
print_r($percentChange(0, 2)); print "\n";
# No change
print_r($percentChange(0, 0)); print "\n";
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment