What are common pitfalls when iterating over form inputs in PHP using foreach() and how can they be avoided?

One common pitfall when iterating over form inputs in PHP using foreach() is not checking if the input is an array before accessing its value. This can lead to errors when dealing with inputs that have multiple values (e.g., checkboxes with the same name attribute). To avoid this, you can use the is_array() function to check if the input is an array before accessing its value.

foreach ($_POST as $key => $value) {
    if (is_array($value)) {
        foreach ($value as $val) {
            // Process each value
        }
    } else {
        // Process single value
    }
}