tan()
Today, we will discuss the tan() function in PHP. This function is used to calculate the tangent of an angle.
The tan() function in PHP returns the tangent of an angle. The angle must be given in radians, not degrees — this is the single most common source of wrong results, and we'll cover how to convert below.
This chapter explains the syntax, parameters, and return value of tan(), shows runnable examples, and points out the gotchas (radians vs. degrees, the values where tangent blows up to infinity).
What the tan() Function Does
In a right-angled triangle, the tangent of an angle is the ratio of the side opposite the angle to the side adjacent to it. Equivalently, tan(x) = sin(x) / cos(x).
tan() takes a single angle in radians and returns that ratio as a float. A full circle is 2π radians (360°), so π/4 radians equals 45°, whose tangent is 1.
Syntax
tan(float $num): float| Parameter | Type | Description |
|---|---|---|
$num | float | The angle, in radians. |
Return value: a float — the tangent of $num.
Basic Example
Here we pass pi() / 4 radians (45°). The tangent of 45° is exactly 1, though floating-point rounding prints it as something like 0.99999999999999.
Working With Degrees
Most people think in degrees, but tan() only understands radians. Convert first with deg2rad(), or multiply by pi() / 180:
<?php
$degrees = 60;
// Convert degrees to radians before calling tan()
$radians = deg2rad($degrees);
echo tan($radians); // ~1.7320508075689 (√3)
?>Passing 60 directly to tan(60) would compute the tangent of 60 radians — a completely different, meaningless value for this use case.
Gotcha: Where Tangent "Blows Up"
Tangent is sin(x) / cos(x), so it is undefined wherever cos(x) is zero — at 90°, 270°, and so on (π/2 + nπ). In math this is infinity; in floating-point, cos(pi()/2) is a tiny non-zero number, so tan() returns a huge finite value instead of INF:
<?php
echo tan(pi() / 2); // ~1.6331239353195E+16 (very large, not exactly INF)
?>If you need an exact "undefined" check, test whether cos($x) is close to zero before dividing.
Related Functions
tanh()— hyperbolic tangent.atan()— inverse tangent (arctangent), returns an angle in radians.sin()andcos()— the building blocks of tangent.deg2rad()andrad2deg()— convert between degrees and radians.
Conclusion
tan() returns the tangent of an angle expressed in radians. Remember the two essentials: convert degrees to radians first, and be aware that tangent is undefined at 90° + multiples of 180°, where PHP returns a very large value rather than infinity.