0

I am making a calculator application where a person can calculate things. The input of the user wil be stored in a variable called input. So for example:

$input = "3+10/2";

Is there anyway to calculate the answer?

Thijs
  • 715
  • 1
  • 5
  • 10
  • 1
    Remove the quotes - you are treating it as a string, not an integer. – Qirel Feb 11 '16 at 18:23
  • $input = ((3+10)/2); – Alive to die - Anant Feb 11 '16 at 18:24
  • 1
    @Qirel: That's because it is a string. User input is pretty much always a string. – David Feb 11 '16 at 18:25
  • @David Not if you pass it as integers it won't. – Qirel Feb 11 '16 at 18:26
  • @A-2-A: Changing the order of operations changes the result... – David Feb 11 '16 at 18:26
  • @Qirel: And how exactly would you propose that be done here? I think you've misunderstood the question. – David Feb 11 '16 at 18:26
  • if you really want input as string then its basically a data structure question - in which operators will become parent nodes and numbers will be child nodes. You would need tree structure because equation can be complex consisting of brackets – Danish Ahmed Feb 11 '16 at 18:27
  • 2
    Since it's user input, you can't just run it as PHP code by removing quotes as suggested but you can accomplish your goal. Most dangerous method: use [`eval()`](http://php.net/eval). Better method, parse it and then evaluate it. See OP for link. – drew010 Feb 11 '16 at 18:30
  • Take a look at https://gist.github.com/drawmyattention/13a34bf3ad5871a84c28 – cmerriman Feb 11 '16 at 18:32

0 Answers0