Skip to content
PHP Logo

How can the validation logic for email inputs be optimized to reduce redundancy and improve readability in PHP code?

To optimize the validation logic for email inputs in PHP, we can use a regular expression to check if the email format is valid. This approach reduces redundancy by centralizing the validation logic and improves readability by making the code more concise.

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

if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
    echo "Invalid email format";
} else {
    echo "Email is valid";
}