Web Hosting Talk







View Full Version : [php] and math


kneuf
01-19-2004, 09:28 PM
Hi,
I was hopeing that someone can help me with this (I've looked on PHP, but didn't really find anything): I'm trying to make a calculator script and I have 2 files so far, index.php and math.db. In index.php I have the code, and in math.db I have math expressions. I know how to parse and read it into the index.php file, that's not the problem. The math.db is in the format of:

data1::data2::data3

data3 is what I have trouble with. Say it says:

[num1]+[num2]

I need to replace [num1]+[num2] with something like 1+1. My problem is that it printes 1+1, not 2. If you can understand my question, how do you make it so that it evaluates it?

Thanks.

sonic10
01-19-2004, 10:26 PM
humm.. is this what your after....

<?php
$var1=$num1;
$var2=$num2;
$total = $var1 + $var2;
print "The total ='$total'";
?>

kneuf
01-19-2004, 10:33 PM
Ya, sort of. My problem is that one file contains stuff like (the math.db file)

0001::Add::[var1]+[var2]

in index.php file, i have a function that converts [var1] to $var1, [var2] $var2, etc. But when I output it, it doesn't evaluate it, it just prints out 1+1 (or whatever I set for $var#'s).

digitok
01-19-2004, 11:37 PM
Show us the code for index.php

Burhan
01-20-2004, 05:37 AM
Is this what you are after?



$data = "0001::Add::2+3";

$parts = explode("::",$data);

if ($parts[1] == "Add") { $operator = "+"; }

$operands = explode($operator,$parts[2]);

$var1 = $operands[0];
$var2 = $operands[1];

eval("\$result = ".$var1.$operator.$var2.";");

echo "Result is ".$result;

digitok
01-20-2004, 06:20 AM
Nice one, fyre :) I was gonna fix his code, but he can use yours now ;)

kneuf
01-20-2004, 11:14 AM
thanks guys I will check it out later, I'm at school right now

kneuf
01-20-2004, 11:17 PM
sorry it didn't do quite what i need... the math.db file will contain many more than just the one above, and they will be more complex... how do i make the script 'parse' the data, not just print it out?

-thanks

kneuf
01-21-2004, 04:47 PM
any ideas? if not I'll have to do it the hard way... thanks for the help so far though...

kneuf
01-21-2004, 05:09 PM
nevermind i figured it out myself ;). i used this in part of my code:

eval("\$return=" . $return . ";");

hope it helps someone