find the area of a regular polygon inscribed in a circle in php

To find the area of a regular polygon inscribed in a circle, we need to know the radius of the circle (which is also the distance from the center of the circle to any vertex of the polygon) and the number of sides of the polygon. Here's a PHP function that calculates the area of a regular polygon inscribed in a circle:

main.php
/**
 * Calculates the area of a regular polygon inscribed in a circle.
 *
 * @param int $n The number of sides of the polygon.
 * @param float $r The radius of the circle.
 * @return float The area of the polygon.
 */
function inscribedPolygonArea($n, $r) {
  $angle = pi() / $n; // The central angle of each triangle.
  $side = 2 * $r * sin($angle); // The length of each side of the polygon.
  $area = 0.5 * $n * $side * $r; // The area of the polygon.
  return $area;
}
473 chars
14 lines

To use the function, simply pass in the number of sides and the radius of the circle:

main.php
$area = inscribedPolygonArea(6, 5);
echo "The area of the hexagon is " . $area . ".";
86 chars
3 lines

This would output:

main.php
The area of the hexagon is 64.951905283832.
44 chars
2 lines

gistlibby LogSnag