How can PHP developers optimize the process of counting and displaying query results for user selection in a search function?

When counting and displaying query results for user selection in a search function, PHP developers can optimize the process by using pagination to limit the number of results displayed on each page. This helps improve performance by reducing the amount of data that needs to be processed and displayed at once.

// Define the number of results to display per page
$results_per_page = 10;

// Get the total number of results from the query
$total_results = // Perform query to count total results

// Calculate the total number of pages
$total_pages = ceil($total_results / $results_per_page);

// Determine the current page number
if (isset($_GET['page']) && is_numeric($_GET['page'])) {
    $current_page = $_GET['page'];
} else {
    $current_page = 1;
}

// Calculate the starting result for the current page
$start = ($current_page - 1) * $results_per_page;

// Perform query to fetch results for the current page
$results_query = // Perform query to fetch results for current page

// Display results
foreach ($results_query as $result) {
    // Display result data
}

// Display pagination links
for ($i = 1; $i <= $total_pages; $i++) {
    echo "<a href='?page=$i'>$i</a> ";
}