What are the best practices for organizing PHP code within HTML forms?

When organizing PHP code within HTML forms, it is best practice to separate the PHP logic from the HTML markup to improve readability and maintainability of the code. One way to achieve this is by placing the PHP code at the top of the file or in a separate file and using PHP tags to echo variables or execute functions within the HTML form.

<?php
// PHP logic to process form data
if ($_SERVER["REQUEST_METHOD"] == "POST") {
    // Process form data here
    $name = $_POST['name'];
    $email = $_POST['email'];
    
    // Additional processing or validation
}

?>

<!DOCTYPE html>
<html>
<head>
    <title>Form Example</title>
</head>
<body>
    <form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>">
        <label for="name">Name:</label>
        <input type="text" name="name" id="name" value="<?php echo isset($name) ? $name : ''; ?>"><br>
        
        <label for="email">Email:</label>
        <input type="email" name="email" id="email" value="<?php echo isset($email) ? $email : ''; ?>"><br>
        
        <input type="submit" value="Submit">
    </form>
</body>
</html>