Dinuka Thilanga
Dinuka Thilanga

Reputation: 4330

Numeric operation using string

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; 

Upvotes: 5

Views: 164

Answers (4)

xdazz
xdazz

Reputation: 160943

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);

Upvotes: 10

Can Vural
Can Vural

Reputation: 2077

<?php

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

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

Upvotes: 4

Val
Val

Reputation: 17542

switch($option){
 case '+':
    $newValue =  222 + $value;
  break;

}


echo $newValue;

hope it helps

Upvotes: 4

Your Common Sense
Your Common Sense

Reputation: 157989

$oldValue = 222;
switch ($option) {
  case '+':
  $newValue = $oldValue + $value;
  break;
}

Upvotes: 5

Related Questions