February, 2008

Calculate arithmetic string in PHP

I was working on a PHP project where I was supposed to store user’s data which is an arithmetic string and then display its output.
e.g.
A user will input strings like
2+3+4+5-2-3-4+1*1
Output 6 should be given.

First I thought of implementing this, then I thought how easy it would be of we can simply compute a string in PHP. While discussing this with a friend he told me about a function called eval (). Jackpot! Just what I needed.

Above is an example of what I did. When we enter a arithmetic string in the box and press submit button then it will calculate this string and will show its output. All this is done by eval("$output = $input;")