Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
PHP program to find the perimeter of rectangle
A rectangle is a closed two-dimensional figure with 4 sides where opposite sides are equal and parallel. The perimeter is the total distance around the rectangle, calculated by adding all four sides. In this tutorial, we'll learn different PHP approaches to calculate rectangle perimeter.
Formula
The formula for calculating rectangle perimeter is
Perimeter = 2 × (Length + Breadth)
Where length is the horizontal distance and breadth is the vertical distance.
Direct Formula Approach
The simplest method uses the direct formula to calculate perimeter
<?php $length = 10; $breadth = 5; // Calculate perimeter using the formula $perimeter = 2 * ($length + $breadth); // Output the result echo "Length: $length units
"; echo "Breadth: $breadth units
"; echo "Perimeter: $perimeter units
"; ?>
Length: 10 units Breadth: 5 units Perimeter: 30 units
Using Function
Creating a reusable function for perimeter calculation
<?php
// Function to calculate rectangle perimeter
function calculatePerimeter($length, $breadth) {
return 2 * ($length + $breadth);
}
// Test with different values
$length1 = 15;
$breadth1 = 8;
$perimeter1 = calculatePerimeter($length1, $breadth1);
$length2 = 20;
$breadth2 = 12;
$perimeter2 = calculatePerimeter($length2, $breadth2);
echo "Rectangle 1: Length=$length1, Breadth=$breadth1, Perimeter=$perimeter1
";
echo "Rectangle 2: Length=$length2, Breadth=$breadth2, Perimeter=$perimeter2
";
?>
Rectangle 1: Length=15, Breadth=8, Perimeter=46 Rectangle 2: Length=20, Breadth=12, Perimeter=64
With Input Validation
Adding validation to handle edge cases
<?php
function calculatePerimeterSafe($length, $breadth) {
// Validate inputs
if ($length <= 0 || $breadth <= 0) {
return "Error: Length and breadth must be positive numbers";
}
return 2 * ($length + $breadth);
}
// Test cases
$testCases = [
[10, 5],
[0, 8],
[15, 10],
[-5, 3]
];
foreach ($testCases as $case) {
$result = calculatePerimeterSafe($case[0], $case[1]);
echo "Length: {$case[0]}, Breadth: {$case[1]} ? $result
";
}
?>
Length: 10, Breadth: 5 ? 30 Length: 0, Breadth: 8 ? Error: Length and breadth must be positive numbers Length: 15, Breadth: 10 ? 50 Length: -5, Breadth: 3 ? Error: Length and breadth must be positive numbers
Comparison
| Approach | Time Complexity | Space Complexity | Best Use Case |
|---|---|---|---|
| Direct Formula | O(1) | O(1) | Single calculation |
| Function | O(1) | O(1) | Multiple calculations |
| With Validation | O(1) | O(1) | Production code |
Conclusion
Rectangle perimeter calculation in PHP is straightforward using the formula 2 × (length + breadth). Use functions for reusability and always validate inputs in production applications to handle edge cases properly.
