PHP: Calculating Exponential Growth

Why the caret character is not working in exponential growth calculations in PHP, and what to use instead.

840 views
d

By. Jacob

Edited: 2020-07-27 10:47

exponential growth, php

When calculating exponential growth in PHP, the syntax is a bit different than in standard math; basically, instead of using the caret ^ character to define the exponent, the double asterisk operator ** is used.

The double asterisk is an arithmetic operator used for working with exponentiation.

In order to calculate exponential growth in PHP, we should write the formula like this:

echo 1000*1.1**1; // 1100

Or, using variables:

$s = 1000; // Starting number
$r = 0.10; // The growth rate (10%)
$n = 1; // The exponent

$end_number = $s*(1+$r)**$n;
echo $end_number; // 1100

Addition, Subtraction, and Multiplication still function the same way as when doing math in a spreadsheet or a calculator. I.e.:

$a =10;
$b = 10;

echo $a + $b; // 20
echo $a / $b; // 1
echo $a * $b; // 100

These are all part of the arithmetic operators in PHP. If you are a non English speaker, then this may be one of those cases where it is hard to find an answer when searching in Google.

I did not personally think of searching for "arithmetic", instead I searched for "math operators"; it took me a while to figure out why the caret character was not working as I expected.

Tell us what you think:

  1. In this Tutorial, it is shown how to redirect all HTTP requests to a index.php file using htaccess or Apache configuration files.
  2. How to create a router in PHP to handle different request types, paths, and request parameters.
  3. Tutorial on how to use proxy servers with cURL and PHP
  4. When using file_get_contents to perform HTTP requests, the server response headers is stored in a reserved variable after each successful request; we can iterate over this when we need to access individual response headers.
  5. How to effectively use variables within strings to insert bits of data where needed.

More in: PHP Tutorials