Created
March 12, 2026 01:44
-
-
Save milosh-96/6d1d57880fd370460f99984e39a8e6c7 to your computer and use it in GitHub Desktop.
PHP calculator
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| <?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