The atan2()
function in PHP returns the arc tangent of two variables, y
and x
, representing coordinates.
It calculates the angle (in radians) between the positive X-axis and the point (x, y)
.
Unlike atan()
, it correctly handles the signs of both arguments to determine the correct quadrant.
It returns values from -π to π, making it ideal for directional angle calculations.
Commonly used in geometry, graphics, robotics, and 2D movement logic.
Syntax
atan2(float $y, float $x): float
- $y – Y-coordinate (opposite side)
- $x – X-coordinate (adjacent side)
- Returns – The angle in radians, between -π and π
File Name: atan2-example.php
<?php
echo atan2(1, 1); // ➤ 0.78539816339745 (45 degrees, in radians)
echo "\n";
echo atan2(0, 1); // ➤ 0 (along x-axis)
echo "\n";
echo atan2(1, 0); // ➤ 1.5707963267949 (90 degrees, vertical)
?>
Convert to Degrees
$angle = atan2(1, 1); // ➤ radians
$degrees = rad2deg($angle); // ➤ 45 degrees
echo $degrees;
Use Cases
Use Case | Description |
---|---|
Geometry | Compute angle between two coordinates |
Game development / AI | Calculate direction of movement |
Robotics | Orientation of sensors and wheels |
Physics | Determine vector direction |
Summary
Function | Description |
---|---|
atan2() |
Returns arc tangent of y/x , with quadrant info |
Input | Two floats: y , x |
Output | Float (angle in radians, -π to π) |