## Tutorial: PHP: Calculating a Percentage

The aim of this tutorial is to present a user-written percentage function in PHP, which will then be usable in different contexts. With such a function in hand, a person can calculate multiple percentages in one page, or on many different pages, without having to rewrite the complete function every time.

It only requires a very small knowledge of PHP. We will use variables and create a custom function. Don’t forget that, to set a variable’s value to a number and then use it in calculations, you must not quote it. For example, write `\$var = 12`, and not `\$var = "12"`. For help on variables, you might read the PHP.net Variables page or Jem’s Beginners’ Guide to PHP: Part One, which includes a section on variables.

Also, as this tutorial only shows PHP and no markup (HTML), I will omit the starting and closing PHP tags (`<?php` and `?>`).

### Writing The Function

This part of the tutorial will simply explain the basic function we will create to be able to calculate a percentage. From this, you will be able to calculate the percentage in different situations.

For this tutorial, we will assume that you have two variables: one for the total and one for the amount which you wish to convert into percents. For the moment, the value of either is not needed. We will assume that the total corresponds to the variable \$num_total, while the other amount is \$num_amount. Of course, you can change your variables as needed.

Our function will be called percent(), as it’s a rather easy to remember function. ๐

```function percent(\$num_amount, \$num_total) { \$count1 = \$num_amount / \$num_total; \$count2 = \$count1 * 100; \$count = number_format(\$count2, 0); echo \$count; }```

Now, let’s explain what each line of code does.

• The first line means that we are defining a new function. `function` is a pre-existing command in PHP that enables users to create their own function. Note the presence of two variables, which will be needed to calculate. The PHP.net website has a section on user-defined function.
• The second line (`\$count1 = \$thenumber / \$num_total;`) divides our individual amount by the total.
• The third line (`\$count2 = \$count1 * 100;`) multiplies the result to the previous operating by 100 so as to obtain a percentage.
• The fourth line (`\$count = number_format(\$count2, 0);`) formats the result by removing numbers after the period (e.g. 2.3 will become 2). View the PHP.net number_format() documentation.
• The fifth line (`echo \$count;`) simply displays the final result. If you wish the percentage symbol (%) to show up, you must replace this line by `echo "\$count" . "%";`.
• The last line (}) only closes the function.

A few details not to forget:

• The value in parentheses after percent should be a variable, if you wish to use it across a whole website or otherwise more than once.
• The semi-colons (;) after each line are important to separate functions. Without them, you will get errors.
• If you omit the echo part, the result will simply not be displayed, although it will be calculated.
• Don’t forget to close the function with a closing bracket (}), or you’ll once again get errors.
• \$num_total can be either a variable that remains the same for every function, in which case you can define it before defining the percent() function. If, however, you have more than one total, you will need to define \$num_total each time. For example, if it is equal to 234, you can have `percent(\$num_amount, 234);`.

### Using The Function

In the examples under this section, you can obviously replace the numbers by whichever values suit you best. To use across the page, you must simply write the following:

`percent(\$num_amount, \$num_total);`

Don’t forget that both \$num_amount and \$num_total must either be replaced by numbers or defined previously.

There are four ways you can then use it or modify it. First, you can use the function for two amounts which you know will be fixed. In this case, you still use the same function, but you replace the variables by their values: `percent(34, 152);` will return 22.

Two other ways, similar to one another, is if you have the total or the individual amount identical for each time, but the other variable changes. Then, you would have either:

`percent(23, \$num_total);`

or:

`percent(\$num_amount, 2835);`

Finally, the most versatile option is when both variables have a changing value across the page, in which case you simply write the function as in the first example.

All of this can seem rather obscure, so you can use the “Practical Uses / Examples” section for better understanding.

### Formatting The Results

With the current function, results will be displayed without decimals. If you want more precision, simply increase the “0” in the `number_format() function to another number`. 1 means 1 digit after the decimal, 2 means 2 digits, etc.

### Practical Uses / Examples

I use this function personally on my fanlistings statistics page. The percentage column is generated by this function. This means that the page will be updated as soon as I change the amount of joined fanlistings in one category.

More practical uses coming as I work on a PHP percentage calculator.

1. ### Joma Said:

awesome tutorial, i was looking for something like this! Thanks and good luck!

2. ### Anon Said:

Nice.
However; small tip: it’s bad practice to have your FUNCTION do the output.
If you want to be able to work with the outcome of your function you can’t, simply because it will always echo out the result.

Better would be to have it return the value (return \$count) and then use

echo percentage(34, 62);

3. ### manish sharma Said:

good function man…..keep it up…..

4. ### MR_BIG Said:

Sweet man.

Me Likes….it is good to see that you kept it simple.

Thank you

5. ### Carlos M. dos Santos, Sir Said:

And think I’ve found your blog through Last.fm ‘neighbours’ …

Anyway, long long time ago, I wrote a PHP course (I used to work as assistant in the computing department of a university), and this post made me remember it still exists, and there still is a group at googlegroups.

If you have interest it what I wrote (it’s mostly in freaking brazilian portuguese, but there are worse languages around…) so you can adapt something to your tutorials and stuff, check out the group : http://groups.google.com/group/fatec-so-php

Anyway, you’ve got a cool blog, and you actually write cool stuff here. Keep it up.

6. ### john Said:

Or, you could just clump it all into the one line and save a lot of space:

echo number_format((\$num_amount/\$num_total)*100, 1);

Works fine on a site I help run.

7. ### Mange Said:

If you use this code to calculate the precentage between ex. price on a product it will be “reversed”

if you have a special price, lets say 20% off. it will display 80%.
hope you understand me.

well.. use this code to calculate the real precentage

function percent(\$num_amount, \$num_total) {
\$count1 = \$num_amount / \$num_total;
\$count2 = \$count1 * 100;
\$count3 = 100 – \$count;
\$count = number_format(\$count3, 0);
echo \$count;
}

8. ### Mange Said:

Ops.. The code above dosnt work^

function percent(\$num_amount, \$num_total) {
\$count1 = \$num_amount / \$num_total;
\$count2 = \$count1 * 100;
\$count3 = 100 – \$count2;
\$count = number_format(\$count3, 0);
echo \$count;
}

9. ### Jaroslav Said:

Thanks you,
that helper me ๐