What are the common errors that can occur when using foreach() loops in PHP to iterate through arrays, and how can they be resolved?

One common error when using foreach() loops in PHP is modifying the array being iterated within the loop, which can lead to unexpected behavior. To avoid this, you can make a copy of the array before iterating through it. Another issue is trying to access non-existent keys or values within the array, which can be resolved by using isset() or empty() functions to check if the key exists before accessing it.

// Avoid modifying the array being iterated
$array = [1, 2, 3, 4, 5];
foreach ($array as $key => $value) {
    // Do not modify $array here
}

// Make a copy of the array before iterating
$array = [1, 2, 3, 4, 5];
$arrayCopy = $array;
foreach ($arrayCopy as $key => $value) {
    // Modify $arrayCopy instead of $array
}

// Check if key exists before accessing it
$array = ['foo' => 'bar', 'baz' => 'qux'];
foreach ($array as $key => $value) {
    if (isset($array['baz'])) {
        // Access $array['baz'] safely
    }
}