Backend Development 5 min read

How to Use PHP's sqrt() Function to Calculate Square Roots

This article explains the PHP sqrt() function, demonstrates how to compute square roots for positive and negative numbers, shows how to cast the result to an integer, and highlights important usage considerations with clear code examples.

php中文网 Courses
php中文网 Courses
php中文网 Courses
How to Use PHP's sqrt() Function to Calculate Square Roots

The sqrt() function in PHP calculates the square root of a given number. It accepts a single numeric argument and returns the square root value.

sqrt() Function Usage

Using sqrt() is straightforward: pass the number whose square root you want as the argument. Below is a basic example:

<code>$number = 16;
$result = sqrt($number);
echo "The square root of $number is: $result";</code>

The above code outputs:

<code>The square root of 16 is: 4</code>

In this example, we pass 16 to sqrt() , store the result in $result , and print it with echo .

The sqrt() function can also handle negative numbers, returning a complex number. For instance:

<code>$number = -9;
$result = sqrt($number);
echo "The square root of $number is: $result";</code>

This code outputs:

<code>The square root of -9 is: 3i</code>

Here, passing -9 to sqrt() yields the complex result 3i , which is then printed.

Note that sqrt() accepts only one argument and the argument must be numeric; providing a non‑numeric value will trigger an error, so ensure the input is a valid number before calling the function.

Additionally, sqrt() returns a floating‑point number. If you need an integer result, you can cast the output explicitly:

<code>$number = 25;
$result = (int) sqrt($number);
echo "The square root of $number is: $result";</code>

The above code outputs:

<code>The square root of 25 is: 5</code>

In this case, the floating‑point result from sqrt() is cast to an integer using (int) before printing.

Summary

The sqrt() function is PHP's built‑in way to compute square roots. It takes a single numeric argument and returns a floating‑point result; you can cast it to an integer if needed. Be aware that passing non‑numeric values causes errors, and negative inputs produce complex numbers.

PHP Learning Recommendations

Vue3+Laravel8+Uniapp Beginner to Practical Development Tutorial

Vue3+TP6+API Social E‑commerce System Development Course

Swoole From Beginner to Master Course

Workerman+TP6 Real‑time Chat System Limited‑time Offer

backendfunctiontype castingsqrtComplex Numberssquare root
php中文网 Courses
Written by

php中文网 Courses

php中文网's platform for the latest courses and technical articles, helping PHP learners advance quickly.

0 followers
Reader feedback

How this landed with the community

login Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.