How can a multidimensional array be effectively used to output form errors in PHP?

When dealing with form errors in PHP, a multidimensional array can be effectively used to store and display various error messages for different form fields. By using the field name as the key and an array of error messages as the value, we can easily associate specific errors with specific form fields. This allows for more organized and efficient error handling in form validation.

// Example of using a multidimensional array to store form errors
$errors = array();

// Validate form fields
if(empty($_POST['username'])) {
    $errors['username'][] = 'Username is required';
}

if(empty($_POST['email'])) {
    $errors['email'][] = 'Email is required';
} elseif(!filter_var($_POST['email'], FILTER_VALIDATE_EMAIL)) {
    $errors['email'][] = 'Invalid email format';
}

// Display errors
if(!empty($errors)) {
    foreach($errors as $field => $errorMessages) {
        echo "Errors for $field:<br>";
        foreach($errorMessages as $errorMessage) {
            echo "- $errorMessage<br>";
        }
    }
}