How can the logic of PHP code, such as loops and array handling, be improved to prevent errors like "Undefined offset"?

To prevent errors like "Undefined offset" in PHP code, it is important to properly check the existence of array elements before accessing them. This can be done using conditional statements or functions like isset() to ensure that the array index being accessed actually exists. Additionally, using loops with proper bounds checking can help prevent accessing elements that are out of range.

// Example of improved array handling with bounds checking
$array = [1, 2, 3, 4, 5];

for ($i = 0; $i < count($array); $i++) {
    if (isset($array[$i])) {
        // Process the array element
        echo $array[$i] . "\n";
    }
}