How can PHP be used to calculate the sum of multiple numbers from a form input?
To calculate the sum of multiple numbers from a form input using PHP, you can first retrieve the input values from the form using the $_POST superglobal. Then, loop through the values to sum them up and display the result.
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$numbers = $_POST['numbers'];
$sum = 0;
foreach ($numbers as $number) {
$sum += $number;
}
echo "The sum of the numbers is: " . $sum;
}
?>
<form method="post">
<input type="text" name="numbers[]" />
<input type="text" name="numbers[]" />
<input type="text" name="numbers[]" />
<input type="submit" value="Calculate Sum" />
</form>
Keywords
Related Questions
- What are the potential challenges of integrating HTML code into a PHP file that generates graphics using the GD Library?
- How can PHP be used to dynamically modify the appearance and behavior of elements on a webpage, such as positioning a button on the left side of the screen?
- Are there any specific functions or methods in PHP that can help with formatting strings for file naming conventions?