'How to validate the email format after a user has entered an email in an input using php and return the email of the user?

I'm a beginner and have an input where a user can enter an optional email. I would like to make sure if the user enters something, the email format is correct. I do have a syntaxe error trying to use "&&" but I'm pretty sure it's possible to check 2 conditions (not empty and correct format) in one if. I would also like to replace the echo with the email the user has entered.

Here is the html code

<div method="post">
<label for="email">Email:</label><br>
<input type="text" id="email" name="email"><br>
<button type="submit">submit</button>
</div>

And the PHP

$var = "email";

if (!empty($var)) && (filter_var($var, FILTER_VALIDATE_EMAIL) === true){
    echo "an email has been entered";
 }

Thanks for your help !



Solution 1:[1]

Your code is quite close actually. As noted in the comments, your parenthesis don't fit and filter_var won't return true but the email address (which should be truthy).

So your code should look like this:

$var = "email";

if (!empty($var) && filter_var($var, FILTER_VALIDATE_EMAIL)) {
    echo "an email has been entered";
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Bluehorn