How To: PHP - Roots in PHP (Square Root, Cube Root and nth Root)

To find the nth root of a number in PHP, we can use the pow(base, power) function, for example the cube root of 27 is equal to 27 raised to the power of 1/3, \sqrt[3]{27} = 27^{1/3}, since 3^3 = 27.  In general the nth root of x, \sqrt[n]{x} = x^{1/n}.

To calculate the square root of a number, we can also use the sqrt(number) function.

Example

Some example code showing how to calculate roots in PHP is below:

<?php
// Square root
echo sqrt(49) . "<br />";  // square root of 49
echo pow(49,1/2) . "<br />"; // alternative to square root of 49
echo pow(8,1/2). "<br />"; // square root of 8

// cube root
echo pow(8,1/3). "<br />"; // cube root of 8
echo pow(27,1/3). "<br />"; // cube root of 27

// higher roots
echo pow(390625,1/4). "<br />";
echo "25^4 = " . pow(25,4) . "<br />";

echo pow(1234, 1/6). "<br />";
?>

The output from this example is as follows:

7
7
2.8284271247462
2
3
25
25^4 = 390625
3.2750594908837

1 Star2 Stars3 Stars4 Stars5 Stars (4 votes, average: 5.00 out of 5)
Loading ... Loading ...

5 Comments »

  1. Midhun Girish Said,

    July 22, 2009 @ 11:17 pm

    Thanks for that man..it helped me really(i'm a little weak in maths...)

  2. ikee Said,

    July 26, 2010 @ 7:41 am

    great info.. thanks!

  3. Aurelio De Rosa Said,

    October 31, 2010 @ 7:50 am

    It doesn't work for negative numbers. For example pow(-8,1/3) = -2 but this method says NAN.

  4. Tiposaurus Said,

    February 19, 2011 @ 5:14 pm

    Hmm, I must admit I never tried it with negative numbers. I think it might work for raising them to an integer power, but not otherwise.

    I'm guessing it doesn't do that because there will be some situations where there are no real roots, e.g. sqrt(-1).

  5. Meer Afghan Said,

    November 14, 2011 @ 5:45 am

    Bundles of thanks it helps me in understanding the process

Leave a Comment