Very basic PHP calculator: can't work out what I'm doing incorrectly
The problem is with your last conditional statement being else
instead of another else if
.
else($_POST['operation'] == 'divide') {
echo $first / $second;
}
Having error reporting set to catch and display, would have thrown you something like this:
Parse error: syntax error, unexpected '{' in /var/usr/you/folder/file.php on line 24
Change it to:
else if($_POST['operation'] == 'divide') {
echo $first / $second;
}
Add error reporting to the top of your file(s) which will help find errors.
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
// rest of your code
Sidenote: Displaying errors should only be done in staging, and never production.
That notice will be thrown regardless of which operation is chosen.
else{...}
is used as an exit if something is not set or does meet a criteria in a comparison statement, likeif
andelse if
:http://php.net/manual/en/control-structures.if.php.
It's assuming that else($_POST['operation'] == 'divide')
will always compare to "divide" rather than else { $var=x; }
being an "assign this variable to "x", in turn throwing you an error.
From the manual: http://php.net/manual/en/control-structures.elseif.php
<?php
if ($a > $b) {
echo "a is bigger than b";
} elseif ($a == $b) {
echo "a is equal to b";
} else {
echo "a is smaller than b";
}
?>
Other references:
- http://php.net/manual/en/language.operators.comparison.php
- http://php.net/manual/en/language.operators.assignment.php
Only PHP Code Calculator with Clickable Buttons as Input
This is my truly basic, almost style-less, pure-PHP calculator form:
<!DOCTYPE html>
<html lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Basic PHP Calculator</title>
</head>
<body>
<?php
//var_export($_POST);
//echo "<br>";
$buttons = [1,2,3,'+',4,5,6,'-',7,8,9,'*','C',0,'.','/','='];
$pressed = '';
if (isset($_POST['pressed']) && in_array($_POST['pressed'], $buttons)) {
$pressed = $_POST['pressed'];
}
$stored = '';
if (isset($_POST['stored']) && preg_match('~^(?:[\d.]+[*/+-]?)+$~', $_POST['stored'], $out)) {
$stored = $out[0];
}
$display = $stored . $pressed;
//echo "$pressed & $stored & $display<br>";
if ($pressed == 'C') {
$display = '';
} elseif ($pressed == '=' && preg_match('~^\d*\.?\d+(?:[*/+-]\d*\.?\d+)*$~', $stored)) {
$display .= eval("return $stored;");
}
echo "<form action=\"\" method=\"POST\">";
echo "<table style=\"width:300px;border:solid thick black;\">";
echo "<tr>";
echo "<td colspan=\"4\">$display</td>";
echo "</tr>";
foreach (array_chunk($buttons, 4) as $chunk) {
echo "<tr>";
foreach ($chunk as $button) {
echo "<td",(count($chunk) != 4 ? " colspan=\"4\"" : "") , "><button name=\"pressed\" value=\"$button\">$button</button></td>";
}
echo "</tr>";
}
echo "</table>";
echo "<input type=\"hidden\" name=\"stored\" value=\"$display\">";
echo "</form>";
?>
</body>
</html>
Here is a screenshot while I was testing:
You can see that I've made every button a submit button with the same name, but different values. I use a single hidden input to preserve built expression. There will be many enhancements and considerations beyond this demo, it is up to you how far to go down this rabbit hole.
P.S. For anyone who just unholstered their sidearm, squinted one eye, and sternly uttered "Hey, we don't take kindly to folks like you callin' eval()
in these here parts!". Well, I've endeavored to adequately validate the string to be evaluated. If there is a known hole, please let me know and I'll try to fix it. Alternatively, this is my attempt to re-invent the eval()
process with BOMDAS in mind:
Code: (Demo)
$stored = "2+3*4/6";
$components = preg_split('~([*/+-])~', $stored, 0, PREG_SPLIT_NO_EMPTY | PREG_SPLIT_DELIM_CAPTURE);
while (($index = array_search('*', $components)) !== false) {
array_splice($components, $index - 1, 3, $components[$index - 1] * $components[$index + 1]);
}
while (($index = array_search('/', $components)) !== false) {
array_splice($components, $index - 1, 3, $components[$index - 1] / $components[$index + 1]);
}
while (($index = array_search('+', $components)) !== false) {
array_splice($components, $index - 1, 3, $components[$index - 1] + $components[$index + 1]);
}
while (($index = array_search('-', $components)) !== false) {
array_splice($components, $index - 1, 3, $components[$index - 1] - $components[$index + 1]);
}
echo current($components); // 4
How to make a PHP calculator with 3 variables
your code is not that bad for a beginner, but it still needs some work. Why would you use multiple functions doing more or less the same calculation? You are a ware, that you can call any function multiple time?
Then, check your code. You have a lot of variable mistakes, as you name them different.
Also your variable naming is not so well readable. Give the variables names, so you know what they are supposed to be. On this small code level, this is not that big of a deal. If you work with a lot of code, a good naming can make up a lot!
If you plan to stay on to programming, you want to train yourself to check those issues early. This will save you a lot of time in the future, as you will be trained to do this automatically.
I have more or less corrected your code. I have written some comments to hint out parts and fixes, so you understand what has changed and why.
If you get grades for this calculator project, keep in mind there is still a lot of stuff you can do better. At least if you want to get the best grade.
Check your naming.
Address security issues. (If anyone sees you do this as a beginner,they will be impressed!)
Commenting your code. You have comments, but they are not enough. Comment anything possible so people understand what the code is doing just by reading the comment.
Some corrected code:
<?php
// you only need one function. why would you need a lot of functions doing the same?
function calculate($x, $y, $op) {
// calculate $prod using switch (case) statement
switch($op) {
case '+':
$prod = $x + $y;
break;
case '-':
$prod = $x - $y;
break;
case '*':
$prod = $x * $y;
break;
case '/':
if ($y == 0) {$prod = "∞";}
else {$prod = $x / $y;}
break;
}
// do return your result AFTER the switch. else you will not get any results in most cases
return $prod;
}
// you can do this, but keep in mind, this is more or less a security issue!
// you may want to check how to work with $_GET variables. as it is for school work, it is not critical yet,
// but if you plan to use php in future you may want to have a look at some ways to avoid problems.
extract($_GET);
// in this example is no need to predefine the variables as you had it, as wich each post the value get lost and it only uses the information from $_GET
?>
<html>
<head>
<title>PHP Calculator Version 2.12</title>
</head>
<body>
<h3>PHP Calculator (Version 2.12)</h3>
<form method="get" action="<?php echo $_SERVER['PHP_SELF']; ?>">
x = <input type="text" name="x" size="5" value="<?php print $x; ?>" /> op1 =
<select name="op1">
<option value="+" <?php if ($op1=='+') echo 'selected="selected"';?>>+</option>
<option value="-" <?php if ($op1=='-') echo 'selected="selected"';?>>-</option>
<option value="*" <?php if ($op1=='*') echo 'selected="selected"';?>>*</option>
<option value="/" <?php if ($op1=='/') echo 'selected="selected"';?>>/</option>
</select> y = <input type="text" name="y" size="5" value="<?php print $y; ?>" /> op2 =
<select name="op2">
<option value="+" <?php if ($op2=='+') echo 'selected="selected"';?>>+</option>
<option value="-" <?php if ($op2=='-') echo 'selected="selected"';?>>-</option>
<option value="*" <?php if ($op2=='*') echo 'selected="selected"';?>>*</option>
<option value="/" <?php if ($op2=='/') echo 'selected="selected"';?>>/</option>
</select> z = <input type="text" name="z" size="5" value="<?php print $z; ?>" />
<input type="submit" name="calc" value="Calculate" />
</form>
<?php
if(isset($calc)) {
if (is_numeric($x) && is_numeric($y) && is_numeric($z)) {
// if you use OR / AND or any other operator, make sure both sides have a counterpart to work with.
if ($op1 == '*' or $op1 == '/') {
// you can use the same function multiple times as seen below
$prod1 = calculate($x, $y, $op1);
$prod2 = calculate($prod1, $z, $op2);
}
else if ($op2 == '*' or $op2 == '/') {
$prod1 = calculate($y, $z, $op2);
$prod2 = calculate($x, $prod1, $op1);
}
else {
$prod1 = calculate($x, $y, $op1);
$prod2 = calculate($prod1, $z, $op2);
}
// make sure what you print does also exist!
echo "<p>$x $op1 $y $op2 $z = $prod2 </p>";
}
else {
// unaccepatable values
echo "<p>x, y, and z values are required to be numeric ...
please re-enter values</p>";
}
}
?>
</body>
</html>
Simple PHP Calculator, issues with logic and output
Thats because of the order of execution. In the first case your code if first concatenating $tall1 to the string "Svaret er: ". And then it adds $tall2.
You can fix it by surrounding the math part with parenthesis.
switch($operator)
{
case "plus":
echo "Svaret er: " . ($tall1 + $tall2);
break;
case "minus":
echo "Svaret er: " . ($tall1 - $tall2);
break;
case "multi":
echo "Svaret er: " . ($tall1 * $tall2);
break;
case "divisjon":
echo "Svaret er: " . ($tall1 / $tall2);
break;
}
How to make PHP Calculator Store and Display History
To work with sessions, first of all you may start any PHP script using $_SESSION with session_start():
<?php
session_start();
Then you can initialize an array result storage with:
if (!isset($_SESSION['results'])){
$_SESSION["results"] = [];
}
And add stored values using :
$_SESSION["results"][]="New result";
For example, you can store the operation result after calculation, like here:
if ($operation == '+') {
$Result = ((int)$numberOne + (int)$numberTwo);
$_SESSION["results"][]="$numberOne + $numberTwo = $Result";
}
You may use any string/number/array values to store the result in a more structured way if you want. Then you can add your saved results to the HTML form page (must be a .php
file, not .html
), for example:
<div class="logs">
<?php echo implode("<br>",$_SESSION["results"]); ?>
</div>
To clean/reset the results array, you can add a new 'reset' operation or something like this to do that:
if ($operation == 'reset'){
$_SESSION["results"] = [];
}
Related Topics
How to Update Field to Add Value to Existing Value
Regex for Only Allowing Letters, Numbers, Space, Commas, Periods
How to Install Imagick/Imagemagick PHP Extension on Windows 7
Dompdf Not Rendering Images from the Server But Is Rendering from External Source
Php Fatal Error: Uncaught Pdoexception: Could Not Find Driver
How to Set Current Date as Default Value of an Input
I Have Three Columns, I Want to Combine Them All in One Main_Table
Add Space After Every 4Th Character
Laravel: Products,Categories and Subcategories! (Relation Ships)
Remove License Check from Script Code in Codeigniter
Checking Dates If Between Range of Dates in Laravel 5
Laravel Eloquent How to Get the Minimum Value That Is Not Null
How to Pass an Array Within a Query String
Get Selected Option in PHP Without Pressing Submit
Laravel, Failed to Authenticate on Smtp Server With Username "" Using 3 Possible Authenticators
How to Call Function of One PHP File from Another PHP File and Pass Parameters to It