Webbserverprogrammering 1

Show sourcecode

The following files exists in this folder. Click to view.

webbsrvprg/exercises/formular/

Formular1.php
Formular1Svar.php
Formular2.php
Formular2Svar.php
Formular3.php
Formular3Svar.php
Formular4.php
Formular4Svar.php
Formular5.php
Formular5Svar.php
Formular6.php
Formular6Svar.php
Formular7.php
Formular7Svar.php
Formular8.php

Formular8.php

44 lines UTF-8 Windows (CRLF)
<?php
function beraknaMedelvarde(float $tal1, float $tal2, float $tal3): float {
    return (
$tal1 + $tal2 + $tal3) / 3;
}

$tal = null;
$medelvarde = null;
if (
$_SERVER["REQUEST_METHOD"] === "POST") {
    
$inmatning = [$_POST["tal1"] ?? null, $_POST["tal2"] ?? null, $_POST["tal3"] ?? null];
    if (
count(array_filter($inmatning, "is_numeric")) === 3) {
        
$tal = array_map("floatval", $inmatning);
        
$medelvarde = beraknaMedelvarde($tal[0], $tal[1], $tal[2]);
    }
}
?>
<!DOCTYPE html>
<html lang="sv">
<head>
    <meta charset="UTF-8">
    <title>Formulär 8 - medelvärde</title>
</head>
<body>
    <h1>Beräkna medelvärde</h1>
    <form action="Formular8.php" method="POST">
        <p><label for="tal1">Tal 1:</label>
        <input type="number" step="any" id="tal1" name="tal1" value="<?= htmlspecialchars((string) ($tal[0] ?? ""), ENT_QUOTES, "UTF-8") ?>" required></p>
        <p><label for="tal2">Tal 2:</label>
        <input type="number" step="any" id="tal2" name="tal2" value="<?= htmlspecialchars((string) ($tal[1] ?? ""), ENT_QUOTES, "UTF-8") ?>" required></p>
        <p><label for="tal3">Tal 3:</label>
        <input type="number" step="any" id="tal3" name="tal3" value="<?= htmlspecialchars((string) ($tal[2] ?? ""), ENT_QUOTES, "UTF-8") ?>" required></p>
        <button type="submit">Beräkna</button>
    </form>
    <?php if ($medelvarde !== null): ?>
        <h2>Resultat</h2>
        <p>Tal 1: <?= htmlspecialchars((string) $tal[0], ENT_QUOTES, "UTF-8") ?></p>
        <p>Tal 2: <?= htmlspecialchars((string) $tal[1], ENT_QUOTES, "UTF-8") ?></p>
        <p>Tal 3: <?= htmlspecialchars((string) $tal[2], ENT_QUOTES, "UTF-8") ?></p>
        <p>Medelvärde: <?= htmlspecialchars((string) $medelvarde, ENT_QUOTES, "UTF-8") ?></p>
    <?php elseif ($_SERVER["REQUEST_METHOD"] === "POST"): ?>
        <p>Ange tre giltiga tal.</p>
    <?php endif; ?>
</body>
</html>