Server-Side Scripting/Iteration/PHP
Appearance
index.php
[edit | edit source]<?php
// Demonstrates conditions, while loops and for loops using
// Celsius and Fahrenheit temperature conversion tables.
//
// References:
// https://www.mathsisfun.com/temperature-conversion.html
// https://en.wikibooks.org/wiki/PHP_Programming
// https://www.tutorialspoint.com/php/php_get_post.htm
$FORM = '
<h1>Temperature Conversion</h1>
<form method="POST">
<p><label for="start">Start:</label>
<input type="text" id="start" name="start" value="0"></p>
<p><label for="stop">Stop:</label>
<input type="text" id="stop" name="stop" value="100"></p>
<p><label for="increment:">Increment</label>
<input type="text" id="increment" name="increment" value="10"></p>
<p><input type="submit" name="submit" value="Celsius">
<input type="submit" name="submit" value="Fahrenheit"></p>
</form>
';
main();
function main() {
switch($_SERVER["REQUEST_METHOD"]) {
case "GET":
echo $GLOBALS["FORM"];
break;
case "POST":
$start = intval($_POST["start"]);
$stop = intval($_POST["stop"]);
$increment = intval($_POST["increment"]);
$submit = $_POST["submit"];
if ($submit == "Celsius") {
echo process_celsius($start, $stop, $increment);
}
else if ($submit == "Fahrenheit") {
echo process_fahrenheit($start, $stop, $increment);
}
else {
echo "Unexpected submit value: " . submit;
}
break;
default:
echo "Unexpected request method:" . $_SERVER["REQUEST_METHOD"];
break;
}
}
function process_celsius($start, $stop, $increment) {
$result = "<h1>Temperature Conversion</h1>";
$result = $result . "<table><tr><th>Celsius</th><th>Fahrenheit</th></tr>";
$celsius = $start;
while ($celsius <= $stop) {
$fahrenheit = $celsius * 9 / 5 + 32;
$result = $result . "<tr><td>" . $celsius . "</td>";
$result = $result . "<td>" . number_format($fahrenheit, 1) . "</td></tr>";
$celsius += $increment;
}
$result = $result . "</table>";
return $result;
}
function process_fahrenheit($start, $stop, $increment) {
$result = "<h1>Temperature Conversion</h1>";
$result = $result . "<table><tr><th>Fahrenheit</th><th>Celsius</th></tr>";
for ($fahrenheit = $start; $fahrenheit <= $stop; $fahrenheit += $increment) {
$celsius = ($fahrenheit - 32) * 5 / 9;
$result = $result . "<tr><td>" . $fahrenheit . "</td>";
$result = $result . "<td>" . number_format($celsius, 1) . "</td></tr>";
}
$result = $result . "</table>";
return $result;
}
?>
Try It
[edit | edit source]Copy and paste the code above into the following free online development environment or use your own PHP compiler / interpreter / IDE.