-
-
Save logikinc/0cfd779538154e647db48634e4914e65 to your computer and use it in GitHub Desktop.
Calculate Percentage Change
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<? | |
/** | |
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