Tutorial: How to Find a Percentage Using PHP A quick and easy way to find percentages in php

Before I get started, I wanted to say that this is just one way to do it. It’s the way I do it but there are definitely other equally effective ways of doing it. With that said, let’s get started.

As always, we have the opening php tag and a commented description of the function of the script.

<?php
// find the percentage

For the purpose of this exercise, let’s say that we have 50 seeds. We plan to give 22 of those away. We want to find out what percentage of the seeds we’re giving away.

  
  // variables
  // the seeds we're giving away 
  $actualvalue = "22";
  // the total amount of seeds we have
  $maxvalue = "50";

To figure out the percentage, you would want to first divide the amount of seeds you’re giving away by the total amount of seeds you have and then multiple the answer by 100.

  // let's do the math first
  $findpercent = 100 * ($actualvalue/$maxvalue);

This next step is to account for numbers that come back with something other than a whole number. We use PHP’s number_format for this. A good example of why you need to do this step is for cases like this one: 3 out of 47. Its answer from the first step (3/47) is 0.0638297872340426. Multiply that by 100 and you still have a long, ugly number: 6.382978723404255. PHP’s number_format will give you the whole number and cut off everything after the decimal.

  
  $percent = number_format($findpercent);

Side note: number_format can also be used to show whichever amount of places after the decimal you want to show. In this case, however, number_format($yourvariable) won’t show the decimal or anything after the decimal.

Lastly, we output the result and close the script.

  // now echo the percent
  echo "You have $percent% of something!";

  ?> 

The end result:
A simple percentage output.

And that’s it. It doesn’t get any easier than that. 😀 As always, if you have any questions or comments, feel free to post them below.

If you found this post useful, leave a comment below!

Leave a Reply

Your email address will not be published. Required fields are marked *