Calculates an angle from y and x coordinates while preserving the correct quadrant.
What Is atan2() in PHP?
Calculates an angle from y and x coordinates while preserving the correct quadrant.
Its syntax is:
atan2(float $y, float $x): float
Parameters:
$y— Accepted as float; required argument.$x— Accepted as float; required argument.
Return type: float. The argument order is y first, x second. Unlike atan(y / x), atan2() correctly distinguishes quadrants and handles x=0.
Availability: Available in standard PHP.
Example 1: Basic Usage
<?php
echo rad2deg(atan2(1, 1));
Output:
45
The argument order is y first, x second. Unlike atan(y / x), atan2() correctly distinguishes quadrants and handles x=0.
Example 2: A Different Input
<?php
echo rad2deg(atan2(1, -1));
Output:
135
The argument order is y first, x second. Unlike atan(y / x), atan2() correctly distinguishes quadrants and handles x=0.
Practical Example: Applying It in a Program
<?php
$points = [[1, 0], [0, 1], [-1, 0]];
foreach ($points as [$horizontal, $vertical]) { echo rad2deg(atan2($vertical, $horizontal)) . PHP_EOL; }
Output:
0
90
180
The argument order is y first, x second. Unlike atan(y / x), atan2() correctly distinguishes quadrants and handles x=0.
Important Behavior and Edge Cases
- Key behavior: The argument order is y first, x second. Unlike atan(y / x), atan2() correctly distinguishes quadrants and handles x=0.
- Environment: Available in standard PHP.
Comparison With Related Functions
| Function | Purpose |
|---|---|
atan2() | calculates an angle from y and x coordinates while preserving the correct quadrant. |
atan() | atan() takes one ratio and does not independently identify the coordinate quadrant; atan2() uses y and x. |
Common Beginner Mistakes
| Mistake | Correct Approach |
|---|---|
| Ignoring this behavior: The argument order is y first, x second | The argument order is y first, x second. Unlike atan(y / x), atan2() correctly distinguishes quadrants and handles x=0. |
Key Takeaways
- calculates an angle from y and x coordinates while preserving the correct quadrant.
- The argument order is y first, x second. Unlike atan(y / x), atan2() correctly distinguishes quadrants and handles x=0.
- Available in standard PHP.
Summary: The argument order is y first, x second. Unlike atan(y / x), atan2() correctly distinguishes quadrants and handles x=0.