View Full Version : How to have mathematic operators in a submit form?

10-09-2009, 11:27 PM
Hey there, I'm clueless about how to do this and I was thinking how could you add support of mathematic operators in a submit form?

Kind of like Google, where you can type in 2*2 or 2x2 in the search box and it gives you an answer.

Thanks! :)

10-10-2009, 02:26 AM
Use sscanf to format you're input and then perform the operation. You'll need to choose a format for it to be of any use though:

list($lhs, $op, $rhs) = sscanf($input, "%d%s%d");
$op = trim($op);
$result = 0;
switch ($op)
case '+':
$result = $lhs + $rhs;
case '-':
$result = $lhs - $rhs;
case '*':
case 'x':
$result = $lhs * $rhs;
case '/':
$result = $lhs / $rhs;

You'll need some error checking. You won't need to atoi this at all since php can interpret strings as numbers.