PHP sqrt() returns the square root of a number. The examples below show how the call behaves, where it is useful, and which limitations matter.
What Is sqrt() in PHP?
Returns the square root of a number.
Its call structure is:
sqrt($num)
The arguments identify the values or resources passed to sqrt(). Read the examples with attention to the type of each supplied argument and to whether the function modifies its input or returns a separate result.
Example 1: Basic Usage
This example introduces sqrt with a direct call and a small, readable input.
<?php
echo sqrt(81);
Output:
9
Returns the square root of a number. Negative inputs yield NAN rather than a real-valued answer.
Example 2: Another Behavior or Input
Compare this input with the previous example: changing the data or option can affect how sqrt behaves.
<?php
var_dump(is_nan(sqrt(-1)));
Output:
bool(true)
The changed input illustrates why output may differ with the chosen values or environment. Negative inputs yield NAN rather than a real-valued answer.
Practical Example: Using the Feature
The following example incorporates sqrt into a workflow. Values such as paths, connection handles and configuration options must come from trusted application settings.
<?php
$squaredDistance = 9 * 9 + 12 * 12; echo sqrt($squaredDistance);
Output:
15
In a real application, check each operation result, validate values before use and clean up acquired resources. Negative inputs yield NAN rather than a real-valued answer.
Important Behavior and Edge Cases
- Purpose: Returns the square root of a number.
- Key limitation: Negative inputs yield NAN rather than a real-valued answer.
- Failure handling: Check return values and handle invalid inputs and unavailable operating-system or extension features where relevant.
Comparison With Related Functions
| Function or Approach | Best Fit |
|---|---|
sqrt() | Returns the square root of a number. |
pow() | Raises a number to a given exponent rather than specifically taking a square root. |
Common Beginner Mistakes
| Mistake | Correct Approach |
|---|---|
| Negative inputs yield NAN rather than a real-valued answer. | The correct approach depends on this behavior: Negative inputs yield NAN rather than a real-valued answer. |
| Ignoring errors or cleanup after the operation. | Validate inputs and check each result; close files, restore settings or release resources when the operation requires it. |
Key Takeaways
- Returns the square root of a number.
- Negative inputs yield NAN rather than a real-valued answer.
- Use the examples as starting points, and adapt environmental paths, resources and permissions rather than assuming fixed results.
sqrt is useful when its specific behavior fits the problem. The safest implementations combine the correct API with input validation, error checking and resource cleanup.