atan2() uses both coordinate components to determine the correct quadrant and returns the angle in radians. Convert the result with rad2deg() when you need degrees.
$y = 1;
$x = 1;
$angle = atan2($y, $x);
echo rad2deg($angle); // 45
The examples below build from the basic call to practical variations and edge cases.
<?Php
echo atan2(0,2); // Output is 0
echo "<br>";
echo atan2(1,3); // Output 0.32175055439664
echo "<br>";
echo atan2(-1,-3); // -2.8198420991932
echo "<br>";
echo atan2(4,2); // Output is 1.1071487177941
echo "<br>";
echo atan2(2,1); // Output is 1.1071487177941
echo "<br>";
echo atan2(90,180); // Output is 0.46364760900081
?>
atan2(float $y, float $x): float;
The first argument is the y-coordinate and the second is the x-coordinate. The return value is an angle in radians.
$x = 1;
$y = 1;
echo atan2($y, $x); // Output: 0.78539816339745 (45 degrees in radians)
$x = -1;
$y = -1;
echo atan2($y, $x); // Output: -2.3561944901923 (-135 degrees in radians)
$x = 5;
$y = 0;
echo atan2($y, $x); // Output: 0 (Horizontal line along the positive x-axis)
The function returns a result between -π and π.Author & Instructor at plus2net
I write and maintain practical tutorials on Python, PHP, SQL, JavaScript, HTML, jQuery, and web development at plus2net. The tutorials focus on clear explanations, working examples, and code that readers can test and adapt while learning.