Performing maths operations on PHP variables
Posted: Wed Jul 16, 2008 7:36 am
I am writing a script that performs some simple mathematics (adding, subtracting, dividing and multiplying). I started by declaring some values that could be used (up to six, $a, $b, $c, $d, $e, $f). Users can then manipulate these functions by using simple commands, such as:
.
So, in this case, if $a = 6 and $b = 3, it would return the value 3. This works without a problem when everything is pre-defined. However, the actual sum that is delivered is coming via a form, as follows:
However, as hard as I try, no matter what I try to do, I can only get PHP to print out the input into the form field. I have not been able to make it actually perform the maths. How do I do this?
What is entered into the form is the following:
This is for the ease of use of the person performing the maths. I then use str_replace to convert to variables, so the variable ends up like this:
The variables are, in turn, transferred into their relevant numbers, so in this case, if $a =6 and $b = 3, it ends up like this:
The answer to this sum is, obviously, 3, meaning I have the following variable:
But what I actually want is for PHP to process this, which I haven't been able to work out, despite searching for a solution to this for hours. I've tried using eval(), but haven't got anywhere, and I'm not really sure I want to use eval() anyway, because this page can be accessed by anyone.
Any help would be greatly appreciated. Is it something to do with quotes? In essence, I want PHP to process the following:
Whereas, from the variable, at the moment, it is processing:
So really, I think I'm trying to get rid of the quotes. Please let me know if I've missed any important information out.
Code: Select all
($a - $b)So, in this case, if $a = 6 and $b = 3, it would return the value 3. This works without a problem when everything is pre-defined. However, the actual sum that is delivered is coming via a form, as follows:
Code: Select all
$sum = $_POST['calculation'];What is entered into the form is the following:
Code: Select all
a - bCode: Select all
$a - $bCode: Select all
6 - 3Code: Select all
$sum = 6 - 3Any help would be greatly appreciated. Is it something to do with quotes? In essence, I want PHP to process the following:
Code: Select all
$sum = 6 - 3;Code: Select all
$sum = "6 - 3";