Jump to content

Archived

This topic is now archived and is closed to further replies.

wdmarto

How to convert "2+3" to 5 ?

Recommended Posts

I would like to resolve that problem:
I have this variable:
$str = "2+3";
And I want to print the result of the operation included in that string.
How can I do that?

Thanks.

Mart

Share this post


Link to post
Share on other sites
[code]
<?PHP
$str = "2+3";
echo "$str = ";
echo 2+3;
?>
[/code]

Something like that you mean?

The output would look like this:
[!--quoteo--][div class=\'quotetop\']QUOTE[/div][div class=\'quotemain\'][!--quotec--]
2+3=5
[/quote]

Share this post


Link to post
Share on other sites
Thanks, but what if I don't know the content of the string.

$str = $_REQUEST['op']; // op si a mathematical operator like +, -, *, /
print(2.$str.3); // I want to calculate the result of 2 "operator" 3

I'm not sure that my question is clear enough.
But thanks again.

Mart.


[!--quoteo(post=362232:date=Apr 6 2006, 10:27 AM:name=G F D)--][div class=\'quotetop\']QUOTE(G F D @ Apr 6 2006, 10:27 AM) [snapback]362232[/snapback][/div][div class=\'quotemain\'][!--quotec--]
[code]
<?PHP
$str = "2+3";
echo "$str = ";
echo 2+3;
?>
[/code]

Something like that you mean?



The output would look like this:
[/quote]

Share this post


Link to post
Share on other sites
Someting like this?
[code]
<?php
$operand1 = $_REQUEST['operand1'];
$operand2 = $_REQUEST['operand2'];
$operator = $_REQUEST['operator'];
echo $operand1 . ' ' . $operator . ' ' . $operand2 . ' = ';
switch ($operator) {
    case '+':
        echo $operand1 + $operand2;
        break;
    case '-':
        echo $operand1 - $operand2;
        break;
    case '*':
        echo $operand1 * $operand2;
        break;
    case '/':
        echo $operand1 / $operand2;
        break;
    default:
        echo 'error in operator';
        break;
}
?>
[/code]

Share this post


Link to post
Share on other sites
try using eval(). it can be a bit tricky since you have to make sure it's a valid arithmetic operation, but check this out:
[code]
$val = "2 + 3";
eval("\$x = $val;");
echo $x;
[/code]

that will assign the VALUE of the arithmetic operation in $val to the variable $x and output '5' in this case.

hope this helps

Share this post


Link to post
Share on other sites
Oh! That's what I searched for.
I didn't know how to use eval() function.

Thanks for your help!
I appreciate.

Mart

Share this post


Link to post
Share on other sites

×

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.