How to check if a point is inside a rectangle in PHP

1 Answer

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

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

class Rectangle {
    public $topLeft;
    public $bottomRight;

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

function isPointInsideRectangle(Point $p, Rectangle $rect) {
    return ($p->x >= $rect->topLeft->x && $p->x <= $rect->bottomRight->x &&
            $p->y >= $rect->topLeft->y && $p->y <= $rect->bottomRight->y);
}

$rect = new Rectangle(new Point(0.0, 0.0), new Point(7.0, 7.0));
$p = new Point(3.0, 2.0);

if (isPointInsideRectangle($p, $rect)) {
    echo "The point is inside the rectangle.\n";
} else {
    echo "The point is outside the rectangle.\n";
}



/*
run:

The point is inside the rectangle.

*/

 



answered Jun 22, 2025 by avibootz
...