What are the differences between using a foreach loop and a for loop in PHP for handling large datasets?

When handling large datasets in PHP, using a foreach loop may be less memory efficient compared to a for loop. This is because foreach creates a copy of the array in memory, while a for loop directly accesses the array elements without creating a copy. Therefore, when dealing with large datasets, using a for loop can help reduce memory usage and improve performance.

// Using a for loop to iterate over a large dataset
$largeDataset = range(1, 1000000);

for ($i = 0; $i < count($largeDataset); $i++) {
    // Process each element in the dataset
    $element = $largeDataset[$i];
    // Perform operations on $element
}