In PHP form validation, what are the advantages of using a flexible approach with arrays to store and manage errors compared to other methods?

When validating a form in PHP, it's common to encounter errors that need to be displayed to the user. Instead of using individual error variables for each form field, a more flexible approach is to store errors in an array. This allows for easier management and display of errors, as well as the ability to loop through the array to show all validation messages at once.

// Initialize an empty array to store errors
$errors = [];

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

if(empty($_POST['email'])){
    $errors['email'] = 'Email is required';
}

// Display errors
if(!empty($errors)){
    foreach($errors as $error){
        echo $error . '<br>';
    }
}