PHP Program to Find Area and Perimeter of Rectangle
Last Updated :
27 Feb, 2024
Calculating the area and perimeter of a rectangle is a fundamental geometric operation. The area of a rectangle is given by the formula Area = length * width
, and the perimeter is given by Perimeter = 2 * (length + width)
. In this article, we will explore how to calculate the area and perimeter of a rectangle in PHP using different approaches.
Area and Perimeter of Rectangle using Functions
Calculating the area and perimeter of a rectangle is by defining separate functions for each calculation, namely calculateArea
and calculatePerimeter
.
Example: Illustration of calculating the area and perimeter of a rectangle in PHP using functions.
PHP
<?php
function calculateArea( $length , $width ) {
return $length * $width ;
}
function calculatePerimeter( $length , $width ) {
return 2 * ( $length + $width );
}
$length = 10;
$width = 5;
$area = calculateArea( $length , $width );
$perimeter = calculatePerimeter( $length , $width );
echo "Area of Rectangle: $area\n" ;
echo "Perimeter of Rectangle: $perimeter" ;
?>
|
Output
Area of Rectangle: 50
Perimeter of Rectangle: 30
Time Complexity: O(1)
Auxiliary Space: O(1)
Area and Perimeter of Rectangle using a Class
Calculating the area and perimeter of a rectangle is by defining a class to represent a rectangle and including separate methods for calculating the area and perimeter, namely calculateArea and calculatePerimeter .
Example: Illustration of calculating the area and perimeter of a rectangle in PHP using classes.
PHP
<?php
class Rectangle {
public $length ;
public $width ;
public function __construct( $length , $width ) {
$this ->length = $length ;
$this ->width = $width ;
}
public function calculateArea() {
return $this ->length * $this ->width;
}
public function calculatePerimeter() {
return 2 * ( $this ->length + $this ->width);
}
}
$rectangle = new Rectangle(10, 5);
$area = $rectangle ->calculateArea();
$perimeter = $rectangle ->calculatePerimeter();
echo "Area of the rectangle: $area\n" ;
echo "Perimeter of the rectangle: $perimeter" ;
?>
|
Output
Area of the rectangle: 50
Perimeter of the rectangle: 30
Time Complexity: O(1)
Auxiliary Space: O(1)
Share your thoughts in the comments
Please Login to comment...