What are some best practices for optimizing PHP code to handle large datasets, such as 10,000 records?

When working with large datasets in PHP, it's important to optimize your code to ensure efficient processing and minimal memory usage. One way to achieve this is by using techniques like pagination, caching, and optimizing database queries. Additionally, consider using data structures like arrays or iterators instead of objects for better performance.

// Example of optimizing PHP code to handle large datasets
// Implementing pagination to limit the number of records processed at once

$limit = 100; // Number of records to process per page
$page = isset($_GET['page']) ? $_GET['page'] : 1; // Get current page number

$offset = ($page - 1) * $limit; // Calculate offset for database query

// Perform database query with LIMIT and OFFSET
$query = "SELECT * FROM large_table LIMIT $limit OFFSET $offset";
$result = mysqli_query($connection, $query);

// Process and display results
while ($row = mysqli_fetch_assoc($result)) {
    // Process each record
    echo $row['column_name'] . "<br>";
}

// Pagination links
$total_records = 10000; // Total number of records
$total_pages = ceil($total_records / $limit); // Calculate total number of pages

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