How can PHP be used to pre-fill form fields with previous values within a session without causing errors on initial page load?

When pre-filling form fields with previous values within a session, it's important to check if the form has been submitted before accessing the form values. This can be done by checking if the $_POST array is empty or not. By doing so, we can prevent errors on the initial page load when the form has not been submitted yet.

<?php
session_start();

// Initialize variables
$name = '';
$email = '';

// Check if form has been submitted
if (!empty($_POST)) {
    // Get form values
    $name = isset($_POST['name']) ? $_POST['name'] : '';
    $email = isset($_POST['email']) ? $_POST['email'] : '';

    // Store form values in session
    $_SESSION['name'] = $name;
    $_SESSION['email'] = $email;
} else {
    // Check if session values exist and populate form fields
    $name = isset($_SESSION['name']) ? $_SESSION['name'] : '';
    $email = isset($_SESSION['email']) ? $_SESSION['email'] : '';
}
?>

<form method="post" action="">
    <input type="text" name="name" value="<?php echo $name; ?>" placeholder="Name">
    <input type="email" name="email" value="<?php echo $email; ?>" placeholder="Email">
    <button type="submit">Submit</button>
</form>