What are some best practices for optimizing loops in PHP to improve performance when dealing with large datasets?

When dealing with large datasets in PHP, it's important to optimize loops to improve performance. One way to do this is by minimizing the number of iterations within the loop and reducing unnecessary operations. This can be achieved by pre-fetching data, using efficient data structures, and avoiding unnecessary function calls within the loop.

// Example of optimizing a loop by pre-fetching data
$data = [/* large dataset */];

// Fetch data before the loop to minimize database queries
$query = "SELECT * FROM table";
$result = $pdo->query($query);
$data = $result->fetchAll();

// Loop through the pre-fetched data
foreach ($data as $row) {
    // Process data here
}