-2

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?

2
  • @hakre: how about javascript version? Commented Sep 25, 2013 at 6:54
  • Please use the search. Also if you look for javascript, you should not tag as PHP. - possible duplicate of: Safe evaluation of arithmetic expressions in Javascript Commented Sep 25, 2013 at 7:26

5 Answers 5

1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

thanks ur the winner for Javascript version :)
1

PHP Version

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 

see the result of the code here

1 Comment

thanks ur the winner for PHP version :)
0

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; 

Comments

0

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 

Comments

0

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.'

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.