How to calculate the area, diameter, and circumference of a circle in PHP

2 Answers

0 votes
$radius = 3;
$PI = 3.14;
   
$area = $PI * $radius * $radius;
echo "Area = " . $area . "\n";
   
$diameter = 2 * $radius;
echo "Diameter = " . $diameter . "\n";
   
$circumference = 2 * $PI * $radius;
echo "Circumference = " . $circumference . "\n";
   
 
/*
run:
    
Area = 28.26
Diameter = 6
Circumference = 18.84
    

 



answered Feb 18, 2016 by avibootz
edited 3 hours ago by avibootz
0 votes
eclare(strict_types=1);

/**
 * Immutable Data Transfer Object (DTO) to hold calculated circle metrics.
 * Requires PHP 8.2+.
 */
readonly class CircleMetrics
{
    public function __construct(
        public float $diameter,
        public float $circumference,
        public float $area
    ) {}
}

/**
 * Calculates the diameter, circumference, and area of a circle.
 *
 * @param float $radius The radius of the circle (must be non-negative).
 * @return CircleMetrics An object containing the calculated metrics.
 * @throws InvalidArgumentException If the radius is negative.
 */
function calculateCircleMetrics(float $radius): CircleMetrics
{
    // Guard clause: radius cannot be negative
    if ($radius < 0.0) {
        throw new InvalidArgumentException('Radius cannot be negative.');
    }

    $diameter = 2.0 * $radius;
    $circumference = 2.0 * M_PI * $radius;
    
    // Standard multiplication ($radius * $radius) is more efficient than pow($radius, 2)
    $area = M_PI * ($radius * $radius);

    return new CircleMetrics($diameter, $circumference, $area);
}

// --- Example Usage ---
try {
    $radius = 3.0;

    // Retrieve calculated metrics
    $metrics = calculateCircleMetrics($radius);

    // Output results formatted to 2 decimal places using number_format
    echo "Radius: {$radius}\n";
    echo "Diameter: {$metrics->diameter}\n";
    echo "Circumference: " . number_format($metrics->circumference, 2) . "\n";
    echo "Area: " . number_format($metrics->area, 2) . "\n";
} 
catch (InvalidArgumentException $e) {
    echo "Error: " . $e->getMessage() . "\n";
}


/*
run:

Radius: 3
Diameter: 6
Circumference: 18.85
Area: 28.27

*/

 



answered 3 hours ago by avibootz

Related questions

...