What are some best practices for ensuring that user-entered values remain visible on a form after a calculation is executed in PHP?

When performing calculations on a form in PHP, it's important to ensure that user-entered values remain visible after the calculation is executed. One way to achieve this is by storing the user-entered values in session variables before performing the calculation, and then re-populating the form fields with these values after the calculation is done.

<?php
session_start();

// Check if form is submitted
if ($_SERVER["REQUEST_METHOD"] == "POST") {
    // Store user-entered values in session variables
    $_SESSION['value1'] = $_POST['value1'];
    $_SESSION['value2'] = $_POST['value2'];
    
    // Perform calculation
    $result = $_POST['value1'] + $_POST['value2'];
}
?>

<form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>">
    <input type="text" name="value1" value="<?php echo isset($_SESSION['value1']) ? $_SESSION['value1'] : ''; ?>" />
    <input type="text" name="value2" value="<?php echo isset($_SESSION['value2']) ? $_SESSION['value2'] : ''; ?>" />
    <input type="submit" value="Calculate" />
    
    <?php if (isset($result)) : ?>
        <p>Result: <?php echo $result; ?></p>
    <?php endif; ?>
</form>

<?php
// Clear session variables after form submission
unset($_SESSION['value1']);
unset($_SESSION['value2']);
?>