charlie charlie - 6 months ago 14
PHP Question

PHP calculations with numbers and operators from variables

I have set these variables in PHP:

$settings["operator"] = '/';
$settings["figure"] = '0.6';


I then want to use the above on another variable to work out a calculation, which will end up being:

$total = ($var->price / 0.6);


I tried this:

$total = ($var->price $settings["operator"] $settings["figure"]);


But I'm getting an error because the code is not correct:


Parse error: syntax error, unexpected '$settings' (T_VARIABLE)'


How can I use these variables to create my calculation?

Answer

You will have to make switch or something similar.

switch($settings["operator"]){
  case "/":
    $total = $var->price / $settings["figure"];
    break;

 case "+";
   $total = $var->price + $settings["figure"];
   break;
 //add others under here
}