How to calculate VAT with PHP.

In this tutorial, we will show you how to calculate VAT with PHP.

VAT is a consumption tax that is added to the price of products and services.

Another name for it is “General Sales Tax”, or simply GST.

For the sake of transparency, online shopping websites will often display VAT alongside their net prices. This gives users an idea of how much they will pay in the end.

How to add VAT to the price of a product.

In this example, we will add VAT to the price of a product:

//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);

An explanation of the code above:

  1. We set the VAT rate to 21.5%.
  2. In this example, we set the price of the product to 10. This is the price of the product, excluding VAT.
  3. We then calculate how much VAT needs to be added to the original price. We do this by dividing the price by 100 and then multiplying it by 21.5 (our VAT percentage).
  4. After that, we add the VAT to the original price.
  5. Finally, we print out the gross price.

How to calculate the VAT rate of a gross price.

In certain cases, you will need to figure out how much of a gross price consists of VAT.

For example:

  • You are working with a database that only contains gross prices.
  • The shop owner does not want to go through the trouble of entering the NET and VAT for each product.

In cases like this, you can do the following:

//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;

An explanation of the PHP code above:

  1. We set the VAT rate to 21.5%. Please note that this might be different in your country.
  2. We create a divisor by adding 1 + (the VAT rate percentage divided by 100).
  3. In this example, we’ve set the gross price to 20.
  4. We work out the net price by dividing the gross price by our divisor.
  5. After that, we determine how much of the gross price is VAT by subtracting the net price from the gross price.
  6. Finally, we print out the result.