Piotrek
Piotrek

Reputation: 11221

How to "do math" inside String?

I have string:

'$a["m"]*$a["m"]'

And I want to do, that $a["m"] turn to its value (for example 5) and my program do the operation (so it will be 5*5 so 25).

EDIT:

I know, I can do this like:

$a["m"].'*'.$a["m"]

But I don't want to ;) I can't. It will be in a string some time and then I plan to calculate that (when all of variables will have values).

I'm making something like "formulas calculator". I write formula in string and now, when my program works, and all of needed data is set, I can calc this string. All of these formulas will be in database, so I get this as a string.

Sorry, I didn't tell exactly what is the problem.

Upvotes: 0

Views: 697

Answers (3)

Amal
Amal

Reputation: 76646

That's what pow() does:

$a['m'] = pow($a['m'], 2);

If your value is stored literally as a string, then you need eval():

$a["m"] = '5';
$str = '$a["m"]*$a["m"]';
$var = eval("\$result = $str;");
echo $result;

Output:

25

And to quote Rasmus Lerdorf, the creator of PHP:

If eval() is the answer, you're almost certainly asking the wrong question.

For your usage, I think it'd be better to use an API such as WolframAlpha.

Get started here: http://products.wolframalpha.com/api/libraries.html

Upvotes: 3

Moeed Farooqui
Moeed Farooqui

Reputation: 3622

First double qoutes " then single '

$a =$a['m'].' * ' . $a['m'];

As per your Updated question:

You want to display the total in a string.

echo "The product of two numbers is:" .$a['m']. '*' .$a['m'] ";

Upvotes: 0

Daryl Gill
Daryl Gill

Reputation: 5524

You should look into concatenation.. The following example should do what you are looking for.

$Var = $a["m"].'*'.$a["m"];

Upvotes: 1

Related Questions