What are the best practices for optimizing PHP code to handle large datasets, such as the 330,000 records mentioned in the forum thread?

To optimize PHP code for handling large datasets like the 330,000 records mentioned, it is important to minimize memory usage and improve performance. One way to achieve this is by using efficient data retrieval methods, such as fetching data in batches instead of all at once. Additionally, utilizing proper indexing and caching techniques can help speed up data processing.

// Example code snippet for fetching data in batches
$batchSize = 1000;
$totalRecords = 330000;
$totalBatches = ceil($totalRecords / $batchSize);

for ($i = 0; $i < $totalBatches; $i++) {
    $offset = $i * $batchSize;
    $query = "SELECT * FROM table LIMIT $offset, $batchSize";
    $result = mysqli_query($connection, $query);

    while ($row = mysqli_fetch_assoc($result)) {
        // Process data here
    }
}