Jump to content

using variable as math operator


Muddy_Funster

Recommended Posts

Curious...If I store values and operators in a DB table and want to use them to perform calculations, how would I go about doing that? eg.

Table has an "operator" column with |* 1.5|/ 0.75|+ 1.2| and I want to do something like desired_value = set_value affected by operator and value from table column, so if set_value = 10 I would want

desired_value = 10 * 1.5

desired_value = 10 / 0.75

desired_value = 10 + 1.2

 

Anything like that possible?

Link to comment
Share on other sites

OK, I'm clearly missing something:

$a = '*2';
$b = '10';
//$c = eval("$b ". $a);  = Unexpected $end
//$c = eval("$b ". $a.";");  = var_dump($c) returns null
//$c = eval("$b  $a;"); = var_dump($c) returns null
//$c = eval($b $a.";"); = Unexpected T_VARIABLE

$d= $b.$a ;
//$c = eval("$d;");  var_dump($c) = Null / var_dump($d) = string(4) "10*2" 

Link to comment
Share on other sites

Eval() executes a (valid) php statement. If you wanted to produce and execute $c =  10 * 1.2;, that's what the "string" you supply to the eval() statement would need to be after all the $a, $b variables have been replaced with their contents.

 

Edit: Specifically -

<?php
$a = '* 1.2';
$b = '10';

eval("\$c = $b $a;");

echo $c;

Link to comment
Share on other sites

Yeah, I thought I was doing that:

$a = '*2';
$b = '10';
$d= $b.$a.";";
$e = 10*2; 
$c = eval("$d");
echo "<pre>";
var_dump($c);
var_dump($d);
var_dump($e);
echo"</pre>";  

Returns:

NULL
string(5) "10*2;"
int(20)

 

Like I said, I have to be missing something here because $e looks exactly like the var_dump of $d to my eyes :suicide:

Link to comment
Share on other sites

An alternate way to do this... keep in mind using EVAL can be dangerous. If you're going to allow user input, be sure to sanitize it AS STRICTLY AS POSSIBLE!

 

<?php

$a = 10;
$b = '*2';

$c = eval('return '.$a.$b.';');

echo $c;

?>

 

Check out the manual entry for eval. Under the 'Return Values' heading, it explains how eval() will populate any variables assigned by it.

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.