Use hypot() when you need to computes the length of the hypotenuse from two numeric sides in a PHP application. The examples below show the actual operation and its limitations.
What Is hypot() in PHP?
Computes the length of the hypotenuse from two numeric sides. The exact signature supported by your installation depends on its PHP version and enabled extensions.
Its syntax is:
hypot(float $x, float $y): float
Parameters and return value: The parameter types, optional arguments, references, and return type are shown in the signature above. Optional parameters are marked with an ellipsis in this reference signature.
Example 1: Basic Usage
<?php
echo hypot(3,4);
Output:
5
Example 2: Different Input or Behavior
<?php
echo hypot(5,12);
Output:
13
Practical Example: Applying the Function
<?php
$points = [[3,4],[8,15]]; foreach ($points as [$width,$height]) echo hypot($width,$height) . PHP_EOL;
Output:
5
17
Important Behavior and Edge Cases
Uses floating-point arithmetic and may lose precision for extreme values.
Comparison With Related Functions
| Approach | Difference |
|---|---|
hypot() | Computes the length of the hypotenuse from two numeric sides. |
| Related operation | sqrt($x*$x + $y*$y) is the direct formula; hypot() is numerically more robust. |
Common Beginner Mistakes
| Mistake | Correct Approach |
|---|---|
| Ignoring the function-specific limitation | Uses floating-point arithmetic and may lose precision for extreme values. |
| Confusing this function with a related operation | sqrt($x*$x + $y*$y) is the direct formula; hypot() is numerically more robust. |
Key Takeaways
- Computes the length of the hypotenuse from two numeric sides.
- Uses floating-point arithmetic and may lose precision for extreme values.
- sqrt($x*$x + $y*$y) is the direct formula; hypot() is numerically more robust.
Use hypot() for the specific operation demonstrated above. Check its prerequisites and handle failure conditions before using it with production data.