How can PHP be used to retain user input values after a calculation is performed on a form?

When a form is submitted and a calculation is performed using PHP, the user input values are typically lost. To retain these values after the calculation, you can store them in PHP variables and then use those variables to pre-fill the form fields when the page reloads. This can be achieved by checking if the form has been submitted, and if so, assigning the submitted values to variables and using those variables as the default values for the form fields.

<?php
// Initialize variables to store user input values
$input1 = '';
$input2 = '';

// Check if the form has been submitted
if ($_SERVER["REQUEST_METHOD"] == "POST") {
    // Retrieve user input values
    $input1 = $_POST['input1'];
    $input2 = $_POST['input2'];
    
    // Perform calculation using the user input values
    $result = $input1 + $input2;
} else {
    // Set default values for the form fields
    $result = '';
}

?>

<form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>">
    <input type="text" name="input1" value="<?php echo $input1; ?>">
    <input type="text" name="input2" value="<?php echo $input2; ?>">
    <input type="submit" value="Calculate">
</form>

Result: <?php echo $result; ?>