How can PHP beginners avoid common pitfalls when working with arrays and loops?

One common pitfall for PHP beginners when working with arrays and loops is not properly initializing variables before using them in loops. To avoid this issue, always initialize variables before using them in loops to prevent unexpected behavior or errors.

// Incorrect way - not initializing the variable before using it in a loop
$numbers = [1, 2, 3, 4, 5];
$sum = 0;

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

echo $sum; // Output: 15

// Correct way - initializing the variable before using it in a loop
$numbers = [1, 2, 3, 4, 5];
$sum = 0;

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

echo $sum; // Output: 15