PHP trigonometric functions such as sin(), cos() and tan() work with radians. Use deg2rad() when your starting angle is in degrees.
$degrees = 60;
$radians = deg2rad($degrees);
echo $radians;
<?Php
echo deg2rad(0); // Output is 0
echo "<br>";
echo deg2rad(90); // Output 1.5707963267949
echo "<br>";
echo deg2rad(180); // Output is 3.1415926535898
echo "<br>";
echo deg2rad(270); // Output is 4.7123889803847
?>
Syntax
float deg2rad(float $degrees);
$degrees is the angle measured in degrees. The returned value is a float in radians.
<?Php
echo round(deg2rad(90),2); // Output is 1.57
?>
sin(), cos() and tan() accept radians. Convert degree input with deg2rad() before calling them.
<?Php
echo sin(deg2rad(90)); // Output is 1
?>
Let us try few more examples
<?Php
echo sin(deg2rad(0)); // Output is 0
echo "<br>";
echo round(sin(deg2rad(180))); // Output is 0
echo "<br>";
echo sin(deg2rad(270)); // Output is -1
echo "<br>";
echo cos(deg2rad(0)); // Output is 1
echo "<br>";
echo cos(deg2rad(180)); // Output is -1
echo "<br>";
echo tan(deg2rad(45)); // Output is 1
?>
$degrees = 90;
$radians = deg2rad($degrees);
echo "Radians: " . $radians; // Output: Radians: 1.5708
echo "Sine of 90 degrees: " . sin($radians); // Output: 1
$degrees_per_second = 30;
$radians_per_second = deg2rad($degrees_per_second);
echo "Radians per second: " . $radians_per_second; // Output: 0.5236
function haversine($lat1, $lon1, $lat2, $lon2) {
$earth_radius = 6371; // Radius of the Earth in km
$dLat = deg2rad($lat2 - $lat1);
$dLon = deg2rad($lon2 - $lon1);
$a = sin($dLat/2) * sin($dLat/2) +
cos(deg2rad($lat1)) * cos(deg2rad($lat2)) *
sin($dLon/2) * sin($dLon/2);
$c = 2 * atan2(sqrt($a), sqrt(1-$a));
return $earth_radius * $c; // Output in km
}
$distance = haversine(51.5074, -0.1278, 40.7128, -74.0060); // London to New York
echo "Distance: " . $distance . " km"; // Output: Distance: 5570.22 km
$angles = [0, 30, 45, 90, 180];
$radians = array_map('deg2rad', $angles);
print_r($radians); // Output: Array ( [0] => 0 [1] => 0.5235987755983 [2] => 0.78539816339745 [3] => 1.5707963267949 [4] => 3.1415926535898 )
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.