5

I have following string.

$option = '+';
$value = '100';

I want create new value using above parameters.

ex:- $newValue = 222 + 100;

How can i do it using above parameters? as following

$newValue = 222 $option $value; 
1

4 Answers 4

10
function operate($a, $b, $opt){
    switch ($opt) {
        case '+':
            $ret = $a + $b;
            break;
        case '-':
            $ret = $a - $b;
            break;
        case '*':
            $ret = $a * $b;
            break;
        case '/':
            $ret = $a / $b;
            break;
        default:
            throw new Exception('Unsupported operation!');
    }
    return $ret;
}

Edit

$option = '+';
echo operate(222,100,$option);
Sign up to request clarification or add additional context in comments.

2 Comments

this is why ur answer is better and my answer is just being lazy :) and assuming user would get it, :) I have edited it a little for you how to call it but +1 for it :)
I wish I could give you another +1 for the throw new Exception :)
5
$oldValue = 222;
switch ($option) {
  case '+':
  $newValue = $oldValue + $value;
  break;
}

1 Comment

$newValue = $oldValue + $value;
4
<?php

$option = '+';
$value = '100';

eval("\$newValue=" . 222 . $option . $value . ';'); 
var_dump($newValue);

2 Comments

This is very dangerous way!
If you call eval() function be sure you have in $option and $value variables only operators which you want to support and numbers.
4
switch($option){
 case '+':
    $newValue =  222 + $value;
  break;

}


echo $newValue;

hope it helps

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.