# Calculating VAT with PHP.

This is a tutorial on how to calculate VAT with PHP. VAT is a consumption tax that is added to the price of products and services (sometimes it is referred to as General Sales Tax or GST). VAT stands for Value Added Tax and you’ll find that it is often displayed on online shopping websites, where prices are sometimes shown excluding / including VAT.

## Adding VAT to the price of a product.

Adding VAT to the price of a product in PHP is straight-forward:

```<?php

//The VAT rate / percentage.
\$vat = 21.5;

//The price, excluding VAT.
\$priceExcludingVat = 10;

//Calculate how much VAT needs to be paid.
\$vatToPay = (\$priceExcludingVat / 100) * \$vat;

//The total price, including VAT.
\$totalPrice = \$priceExcludingVat + \$vatToPay;

//Print out the final price, with VAT added.
//Format it to two decimal places with number_format.
echo number_format(\$totalPrice, 2);```

A drill-down of the code above:

1. We set the VAT rate to 21.5%.
2. For example purposes, I’ve set the price of the product to 10. This is the price of the product EXCLUDING VAT. i.e. The price before VAT has been added.
3. We calculated how much VAT has to be added on to the original price. We did this by dividing the price by 100 before multiplying it by 21.5 (our VAT percentage).
4. We added the VAT to the original price.
5. We printed out the price including VAT (sometimes referred to as the gross price).

## Determining the VAT rate of a gross price.

In certain cases, you’ll find that gross prices have been entered into the database (that or the shop owner doesn’t want to worry about entering the price without tax). In certain cases, you might need to determine how much of the gross price is VAT:

```<?php

//The VAT rate.
\$vat = 21.5;

//Divisor (for our math).
\$vatDivisor = 1 + (\$vat / 100);

//The gross price, including VAT.
\$price = 20;

//Determine the price before VAT.
\$priceBeforeVat = \$price / \$vatDivisor;

//Determine how much of the gross price was VAT.
\$vatAmount = \$price - \$priceBeforeVat;

//Print out the price before VAT.
echo number_format(\$priceBeforeVat, 2), '<br>';

//Print out how much of the gross price was VAT.
echo 'VAT @ ' . \$vat . '% - ' . number_format(\$vatAmount, 2), '<br>';

//Print out the gross price.
echo \$price;```

Explanation of the PHP code above:

1. We’ve set the VAT rate to 21.5%. We will need this to determine how much tax has been added on to the original net price.
2. We create a divisor by adding 1 + (the vat rate percentage divided by 100).
3. For example purposes, I’ve set the gross price to 20.
4. We work out the net price by dividing the gross price by our divisor.
5. We determine how much of the gross price is VAT by subtracting the net price from the gross price.
6. We print out our results.

Hopefully, the math equations in this tutorial helped!