HowTo: PHP – Raise a Number to the Power of Another (exponent in PHP)
You might need to raise a number to the power of another in a PHP script, for example
(sometimes written 3^5), or in general
. This may also be used with negative powers where
. Of course, you’d probably want to do this for more complicated examples!
PHP has a function built in to do this:
pow(x,n).
Examples of ‘Power Of’
Here are some examples, which raise a number to the power of another and display the output. In the examples, <br /> inserts a line break to display the results neatly.
<?php
echo "3^5 = " . pow(3,5) . "<br />"; // 243
echo "2^9 = " . pow(2,9) . "<br />"; // 512
// Anything raised to the power of 0 is 1:
echo "99^0 = " . pow(99,0) . "<br />"; // 1
// Negative powers:
echo "3^-1 = 1/3 = " . pow(3,-1) . "<br />"; // 1/3 = 0.3333
echo "3^-2 = 1/(3^2) = " . pow(3,-2) . "<br />"; // 1/9 = 0.1111
echo "<br />";
// Loop through 2 raised to the 0,1,2,...,10:
for($i=0;$i<=10;$i++)
{
echo "2^" . $i . " = " . pow(2,$i) . "<br />";
}
?>
Output of the example:
3^5 = 243 2^9 = 512 99^0 = 1 3^-1 = 1/3 = 0.33333333333333 3^-2 = 1/(3^2) = 0.11111111111111 2^0 = 1 2^1 = 2 2^2 = 4 2^3 = 8 2^4 = 16 2^5 = 32 2^6 = 64 2^7 = 128 2^8 = 256 2^9 = 512 2^10 = 1024
Good luck! If you have any questions about this article then please post a comment!

