How to calculate the center of a rectangle in PHP

1 Answer

0 votes
class Point {
    public float $x;
    public float $y;

    public function __construct(float $x, float $y) {
        $this->x = $x;
        $this->y = $y;
    }
}

class Rectangle {
    public Point $topLeft;
    public Point $bottomRight;

    public function __construct(Point $topLeft, Point $bottomRight) {
        $this->topLeft = $topLeft;
        $this->bottomRight = $bottomRight;
    }
}

function getCenter(Rectangle $rect): Point {
    $centerX = ($rect->topLeft->x + $rect->bottomRight->x) / 2.0;
    $centerY = ($rect->topLeft->y + $rect->bottomRight->y) / 2.0;

    return new Point($centerX, $centerY);
}

$rect = new Rectangle(new Point(10.0, 20.0), new Point(110.0, 70.0));
$center = getCenter($rect);

printf("Center of the rectangle: (%.2f, %.2f)\n", $center->x, $center->y);



/*
run:

Center of the rectangle: (60.00, 45.00)

*/

 



answered Jun 22, 2025 by avibootz

Related questions

1 answer 167 views
1 answer 194 views
1 answer 177 views
1 answer 172 views
1 answer 205 views
2 answers 286 views
1 answer 183 views
...