How can PHP be optimized to display all possible error messages for both username and email validation simultaneously?

To display all possible error messages for both username and email validation simultaneously in PHP, you can store each error message in an array and then check if the array is empty before proceeding with the registration process. This way, you can display all errors at once to the user.

<?php
$errors = [];

$username = $_POST['username'];
$email = $_POST['email'];

if(empty($username)){
    $errors[] = "Username is required.";
} else if(!preg_match("/^[a-zA-Z0-9]{5,}$/", $username)){
    $errors[] = "Username must be at least 5 characters long and contain only letters and numbers.";
}

if(empty($email)){
    $errors[] = "Email is required.";
} else if(!filter_var($email, FILTER_VALIDATE_EMAIL)){
    $errors[] = "Invalid email format.";
}

if(!empty($errors)){
    foreach($errors as $error){
        echo $error . "<br>";
    }
} else {
    // Proceed with registration process
}
?>