Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
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