im trying to create a calculator that can calculate a large string of values
such as 2 + 3 / 6 - 2 * 6 = …
i store the numbers in array1 and the operations in array2.
when i press equals the code should calculate the answer. here is my code for this
case ‘=’:
$_SESSION[‘calcHistory’][$_SESSION[‘i’]] = $input;
$_SESSION[‘i’]++;
$_SESSION[‘calcType’][$_SESSION[‘x’]] = " = ";
//
if($_SESSION[‘calcHistory’]){
foreach($_SESSION[‘calcHistory’] as $key => $value){
//if a + is found
if($_SESSION[‘calcType’][$key] == “+”){
$_SESSION[‘result’] = $_SESSION[‘result’] + $value + $input;
}else{
$_SESSION[‘result’] = $_SESSION[‘result’] + $value;
}
//if a - is found
//if i do it for subtract it does not work
}
}
break;
if i try to add the code for any other operation other than the plus it does not work, could u please let me know were i am going wrong. thanks
I really hate to say this because I’ve never once used this function due to the dangers of it, but couldn’t you just eval() the input after very careful scrubbing? Maybe this is just an exercise you’re doing, but you are going to get into all kinds of operator precedence issues, etc. and php already has all that handled for you.
Here’s a quick example:
<?php
$expression = '18 + (20/2) * 47';
$value = '?';
if (isset($_POST['calc'])) {
$expression = trim($_POST['calc']);
if (preg_match('#^[\\d \\+\\/\\*\\-\\(\\)]+$#', $expression)) {
$value = eval('return '.$expression.';');
}
$value = ($value === false || $value == '?') ? 'Illegal Expression' : $value;
}
?>
<html>
<head></head>
<body>
<form action="" method="post">
<input type="text" name="calc" value="<?=htmlentities($expression); ?>" /> = <?=htmlentities($value); ?><br />
<input type="submit" value="calculate" />
</form>
</body>
</html>