4th June 2008 - 2 minutes read time
Use the following function to find the percentage value of one number to another. If the $total parameter is zero then zero is returned as this would otherwise result in a division by zero error.
function get_percentage($total, $number)
{
if ( $total > 0 ) {
return round(($number * 100) / $total, 2);
} else {
return 0;
}
}
Here are some examples of the function in action.
echo get_percentage(100,50).'%'; // 50%
echo get_percentage(100,10).'%'; // 10%
echo get_percentage(100,100).'%'; // 100%
echo get_percentage(400,3).'%'; // 0.75%
echo get_percentage(1234,4321).'%'; // 350.16%