Jordy
Jordy

Reputation: 4809

How to use a variable as operator?

how can I do this?

$v1=105;
$v2=90;
if ($value=='subtraction'){
    $operator='-';
}else{
    $operator='+';
}

$new_value=$v1.$operator.$v2;

So it should return 105-90=15 or 105+90=195. But how can I use the $operator variable as a operator? For example this doesn't work:

eval("$new_value=$v1".$operator."$v2");

Thanks for the help!

Upvotes: 1

Views: 129

Answers (4)

capi
capi

Reputation: 1453

Why not make $operator a function?

$v1 = 10;
$v2 = 20;

$substraction = function($a, $b) {
    return $a - $b;
};

[...]

$someString = 'substraction';
echo $$someString($v1,$v2);

Upvotes: 0

joaner
joaner

Reputation: 716

maybe you can change this:

<?php
$v1 = 105;
$v2 = 90;
if($value=='subtraction')
    $v2 *= -1;
$new_value = $v1 + $v2;
?>

Upvotes: 0

Aerik
Aerik

Reputation: 2317

The other answer is better, but if you really want to do something tricky, I think you can have a variable hold a function (instead of an operator).

//untested hypothetical example

$myOperation = function Add($num1, $num2){
  return $num1+$num2;
}

Haven't done that in PHP personally, but I think you can...

Upvotes: 0

gen_Eric
gen_Eric

Reputation: 227270

I suggest not doing this, but to use eval, you'd have to do it like this:

// You need to escape the $ in $new_value
eval("\$new_value = $v1 $operator $v2");

I suggest doing it something like this instead (ie: Don't use a variable for operator, just do the calculation):

$v1=105;
$v2=90;
if ($value=='subtraction'){
    $new_value= $v1 - $v2;
}else{
    $new_value= $v1 + $v2;
}

Upvotes: 5

Related Questions