Skip to content

Instantly share code, notes, and snippets.

@milosh-96
Created March 12, 2026 01:44
Show Gist options
  • Select an option

  • Save milosh-96/6d1d57880fd370460f99984e39a8e6c7 to your computer and use it in GitHub Desktop.

Select an option

Save milosh-96/6d1d57880fd370460f99984e39a8e6c7 to your computer and use it in GitHub Desktop.
PHP calculator
<?php
const numberAInputName = "numberA";
const numberBInputName = "numberB";
const operationInputName = "operation";
$operations = [
"add" => function($a, $b) { return $a + $b;},
"substract" => function($a, $b) { return $a - $b;},
"multiply" => function($a, $b) { return $a * $b;},
"divide" => function($a, $b) { return $a / $b;},
];
$result = null;
$error = null;
$numberA = null;
$numberB = null;
$operation = null;
$showResult = false;
if(isset($_GET[numberAInputName])) {
$numberA = $_GET[numberAInputName];
}
if(isset($_GET[numberBInputName])) {
$numberB = $_GET[numberBInputName];
}
if(isset($_GET[operationInputName])) {
$operation = $_GET[operationInputName];
}
function calculate(int $a, int $b, string $operation = "add") {
global $operations;
return $operations[$operation]($a,$b);
}
if($numberA != null && $numberB != null) {
try {
$showResult = false;
$result = calculate($numberA, $numberB, $operation);
$showResult = true;
$error = null;
}
catch(DivisionByZeroError $ex) {
$error = "You can't divide by zero (0)!";
}
}
?>
<div>
<form action="">
<input type="number" name="numberA" value="<?php echo $numberA ?? 0; ?>">
<select name="operation">
<?php
foreach($operations as $operationKey=>$operationValue):
?>
<option value="<?php echo $operationKey; ?>"><?php echo $operationKey; ?></option>
<?php endforeach; ?>
</select>
<input type="number" name="numberB" value="<?php echo $numberB ?? 0; ?>">
<button type="submit">Calculate</button>
</form>
<?php if($showResult): ?>
<div style="background:#003366; color:white; font-size:2rem;text-align:center;"><?php echo $result; ?></div>
<?php endif; ?>
<?php if($error != null): ?>
<div style="background:red; color:white; font-size:2rem;"><?php echo $error; ?></div>
<?php endif; ?>
</div>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment