Jump to content

How to convert "2+3" to 5 ?


wdmarto

Recommended Posts

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]
Link to comment
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]
Link to comment
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
Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

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.