The sqrt()
function in PHP is used to calculate the square root of a number. It returns the positive square root of the given number. If the input is negative, sqrt()
will return NAN
(Not A Number).
Syntax:
sqrt($number);
- $number: The number for which you want to calculate the square root. It must be a positive number or zero.
Examples:
Example 1: Square root of a positive number
<?php
$number = 16;
$result = sqrt($number);
echo "The square root of $number is $result.";
?>
Output:
The square root of 16 is 4.
Example 2: Square root of zero
<?php
$number = 0;
$result = sqrt($number);
echo "The square root of $number is $result.";
?>
Output:
The square root of 0 is 0.
Example 3: Square root of a negative number
<?php
$number = -9;
$result = sqrt($number);
echo "The square root of $number is $result.";
?>
Output:
The square root of -9 is NAN.
(Note: You can check for NAN
by using is_nan()
.)
Example 4: Square root of a decimal number
<?php
$number = 2.25;
$result = sqrt($number);
echo "The square root of $number is $result.";
?>
Output:
The square root of 2.25 is 1.5.
Handling NAN
:
You can use is_nan()
to check if the result is NAN
.
<?php
$number = -25;
$result = sqrt($number);
if (is_nan($result)) {
echo "The square root of $number is not a number.";
} else {
echo "The square root of $number is $result.";
}
?>
Output:
The square root of -25 is not a number.
This should cover the basics of using the sqrt()
function in PHP!