How can PHP code be optimized to check form input before sending an email?

To optimize PHP code to check form input before sending an email, you can use conditional statements to validate the input data. This can include checking for empty fields, validating email addresses, and ensuring that the input meets any specific requirements. By implementing these checks before sending the email, you can prevent errors and improve the overall user experience.

// Check if form is submitted
if ($_SERVER["REQUEST_METHOD"] == "POST") {
    
    // Check if required fields are not empty
    if (!empty($_POST['name']) && !empty($_POST['email']) && !empty($_POST['message'])) {
        
        // Validate email address
        if (filter_var($_POST['email'], FILTER_VALIDATE_EMAIL)) {
            
            // Send email
            // Add your email sending code here
            echo "Email sent successfully!";
            
        } else {
            echo "Invalid email address!";
        }
        
    } else {
        echo "Please fill out all required fields!";
    }
    
}