How can the use of loops in PHP code be optimized for better performance?

To optimize the use of loops in PHP code for better performance, it is important to minimize the number of iterations and avoid unnecessary operations within the loop. This can be achieved by pre-calculating values outside the loop, using more efficient loop constructs like foreach instead of traditional for loops, and avoiding nested loops whenever possible.

// Example of optimizing loop performance in PHP
// Calculate the sum of an array using foreach loop

$numbers = [1, 2, 3, 4, 5];
$sum = 0;

foreach($numbers as $number) {
    $sum += $number;
}

echo "The sum of the array is: " . $sum;