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 program2
Calculate the area using the formula area = pi() * radius * radius3
Print or return the calculated areaCode
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
| Step | Variable | Value |
|---|---|---|
| 1 | radius | 5 |
| 2 | area | 78.539816339745 |
| 3 | output | Area 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.
| Approach | Time | Space | Best For |
|---|---|---|---|
| Direct calculation | O(1) | O(1) | Simple quick calculation |
| Function method | O(1) | O(1) | Reusable code and clarity |
| Using pow() function | O(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.