0
0
PhpProgramBeginner · 2 min read

PHP Program to Find Area of Circle with Example

To find the area of a circle in PHP, use the formula area = pi() * radius * radius where pi() gives the value of π and radius is the circle's radius.
📋

Examples

Inputradius = 0
OutputArea of circle with radius 0 is 0
Inputradius = 5
OutputArea of circle with radius 5 is 78.539816339745
Inputradius = 10.5
OutputArea of circle with radius 10.5 is 346.360590058274
🧠

How to Think About It

To find the area of a circle, you need the radius. The formula is area = π times radius squared. You get π using PHP's built-in function pi(). Multiply pi by radius times radius to get the area.
📐

Algorithm

1
Get the radius value from the user or set it in the program
2
Calculate the area using the formula area = pi() * radius * radius
3
Print or return the calculated area
💻

Code

php
<?php
$radius = 5;
$area = pi() * $radius * $radius;
echo "Area of circle with radius $radius is $area";
?>
Output
Area of circle with radius 5 is 78.539816339745
🔍

Dry Run

Let's trace the program with radius = 5 through the code

1

Set radius

radius = 5

2

Calculate area

area = pi() * 5 * 5 = 3.1415926535898 * 25 = 78.539816339745

3

Print result

Output: Area of circle with radius 5 is 78.539816339745

StepVariableValue
1radius5
2area78.539816339745
3outputArea of circle with radius 5 is 78.539816339745
💡

Why This Works

Step 1: Using pi() function

The pi() function returns the value of π, which is needed to calculate the circle's area.

Step 2: Calculating area

Multiply π by the radius squared (radius * radius) to get the area.

Step 3: Displaying result

Print the area with a message so the user knows the radius and the calculated area.

🔄

Alternative Approaches

Using a function to calculate area
php
<?php
function circleArea($r) {
    return pi() * $r * $r;
}
$radius = 7;
echo "Area of circle with radius $radius is " . circleArea($radius);
?>
This approach makes the calculation reusable by putting it inside a function.
Using pow() function for exponentiation
php
<?php
$radius = 3;
$area = pi() * pow($radius, 2);
echo "Area of circle with radius $radius is $area";
?>
Using <code>pow()</code> makes the code clearer when squaring the radius.

Complexity: O(1) time, O(1) space

Time Complexity

The calculation uses a fixed number of operations regardless of input size, so it is constant time O(1).

Space Complexity

Only a few variables are used to store radius and area, so space is constant O(1).

Which Approach is Fastest?

All approaches run in constant time; using a function adds readability but no significant speed difference.

ApproachTimeSpaceBest For
Direct calculationO(1)O(1)Simple quick calculation
Function methodO(1)O(1)Reusable code and clarity
Using pow() functionO(1)O(1)Clear exponentiation syntax
💡
Use PHP's built-in pi() function for accurate π value instead of typing 3.14.
⚠️
Forgetting to square the radius and just multiplying by radius once.