PHP Examples

PHP Program - Square Root of a Number



If a number is multiplied by itself (n*n), the final number will be the square of that number and finding the square root of a number is inverse operation of squaring the number. If x is the square root of y, it can be expressed as below:

square root

Alternatively, it can also be expressed as:

x2 = y

Method 1: Using exponent operator of PHP

The exponential (**) operator of PHP can be used to calculate the cube root of a number. Consider the following example.

<?php
$x = 16;
$y = 25;

$x1 = $x**(1/2);
$y1 = $y**(1/2);
echo "Square root of $x is $x1 \n";
echo "Square root of $y is $y1 \n";
?>

The above code will give the following output:

Square root of 16 is 4
Square root of 25 is 5

Method 2: Using sqrt() function of PHP

The sqrt() function of PHP can be used to return square root of a number.

<?php
$x = 16;
$y = 25;

$x1 = sqrt($x);
$y1 = sqrt($y);
echo "Square root of $x is $x1 \n";
echo "Square root of $y is $y1 \n";
?>

The above code will give the following output:

Square root of 16 is 4
Square root of 25 is 5

Method 3: Using pow() function of PHP

The pow() function of PHP can also be used to calculate square root of a number.

<?php
$x = 16;
$y = 25;

$x1 = pow($x, 0.5);
$y1 = pow($y, 0.5);
echo "Square root of $x is $x1 \n";
echo "Square root of $y is $y1 \n";
?>

The above code will give the following output:

Square root of 16 is 4
Square root of 25 is 5