PHP sqrt() function


The sqrt() function in PHP calculates the square root of a given number. The square root of a number xx is a value yy such that y×y=xy \times y = x. The sqrt() function can be used for both positive and negative numbers, but it will return a warning for negative numbers since they do not have real square roots.

Syntax:

sqrt(float $number): float
  • $number: The number for which you want to find the square root. This must be a non-negative floating-point or integer value.
  • Return Value: Returns the square root of the given number as a float.

Example 1: Square Root of a Positive Integer

<?php echo sqrt(16); ?>

Output:

4

Explanation: The square root of 16 is 4, since 4×4=164 \times 4 = 16.

Example 2: Square Root of a Positive Float

<?php echo sqrt(20.25); ?>

Output:

4.5

Explanation: The square root of 20.25 is 4.5, since 4.5×4.5=20.254.5 \times 4.5 = 20.25.

Example 3: Square Root of Zero

<?php echo sqrt(0); ?>

Output:

0

Explanation: The square root of 0 is 0, as 0×0=00 \times 0 = 0.

Example 4: Square Root of a Negative Number

<?php echo sqrt(-4); ?>

Output:

Warning: sqrt() expects parameter 1 to be double, negative value given

Explanation: The sqrt() function generates a warning because the square root of a negative number is not defined in the realm of real numbers.

Example 5: Using sqrt() with a Variable

<?php $number = 49; echo sqrt($number); ?>

Output:

7

Explanation: The variable $number contains 49, and its square root is 7, since 7×7=497 \times 7 = 49.

Key Points:

  • The sqrt() function can only accept non-negative numbers.
  • It returns a float, even when the result is a whole number.
  • It is commonly used in mathematical calculations, such as in geometry, statistics, and physics.

In summary, sqrt() is a straightforward and efficient way to compute the square root of a number in PHP, with built-in error handling for negative inputs.