How can you prevent a for loop from going into negative values when handling pagination in PHP?

When handling pagination in PHP, you can prevent a for loop from going into negative values by checking if the loop variable is less than 1 and setting it to 1 if it is. This ensures that the loop will start at the first page instead of going into negative values.

// Preventing a for loop from going into negative values when handling pagination
$page = $_GET['page'] ?? 1; // Get the current page number from the query parameter, default to 1
if($page < 1){
    $page = 1; // Set the page number to 1 if it is less than 1
}

// Loop through pages starting from the current page
for($i = $page; $i <= $totalPages; $i++){
    // Pagination logic here
}