can we use math formula from other variable/database? example:
var x = 7;
var formula = '+';
var y = 10;
I mean that variables will output = 17
(7 + 10);
but how to implement this formula using Javascript/PHP?
can we use math formula from other variable/database? example:
var x = 7;
var formula = '+';
var y = 10;
I mean that variables will output = 17
(7 + 10);
but how to implement this formula using Javascript/PHP?
For your example you could do this:
var x = 7;
var formula = '+';
var y = 10;
z = eval(x+formula+y); // 17
document.write(z);
But eval
is a big problem for security, and you really shouldn't use it. If you could give more detail on what you're trying to achieve it might be possible to suggest an alternative.
use eval()
in php to run a php code segment:
<?php
$x = 7;
$formula = '+';
$y = 10;
$expression = '$result = ' .$x . ' ' . $formula . ' ' . $y . ";";
echo $expression, "\n"; // $result = 7 + 10;
eval($expression); // run the code
echo $result, "\n"; // ouput 17
In php you can use as below. You can avoid eval
in this way.
$x = 7;
$formula = '+';
$y = 10;
switch ($formula) {
case "+" : $res = $x + $y;
break;
case "-" : $res = $x - $y;
break;
.
.
.
.
}
echo $res;
Something like this should work in PHP and javascript(with a little modification). Also I'd recommend not using eval what so ever because of security reasons.
function math($x, $y, $sign){
switch($sign){
case '+':
return $x + $y;
case '-':
return $x - $y;
case '*':
return $x * $y;
case '/':
return $x / $y;
default:
return;
}
}
$x = 7;
$formula = '+';
$y = 10;
echo math($x, $y, $formula);#returns 17
If you'll be evaluating textual formulas repeatedly with 'eval(),' you may wish to store it within a function - like this:
var formula = "x + y";
var func;
eval("func = function(){return" + formula + "}");
At this point, you could call 'func()' at any time when variables x and y exist within the given scope. For example:
var x = 7;
var y = 10;
var answer = func();
The value of answer would then be '17.'