views:

179

answers:

2

I have a variable that is...

$whatever = "5865/100";

This is a text variable.

I want it to calculate 5865/100 , so that I can add it to other numbers and do a calculation.

Number_format doesn't work, as it just returns "5,865". Whereas I want it to return 58.65

I could do...

$explode=explode("/",$whatever);
if(count($explode)=="2") {
    $whatever = $explode[0]/$explode[1];
}

But it seems rather messy. Is there a simpler way?

+2  A: 

You can use the eval function to evaluate a string as code. However, you have to be careful as to where this code comes from because it will execute anything passed to it, not just simple math. If you knew your string contained a mathematical formula, you could do the following

$answer = 0;
$whatever = "5865/100";

eval ('$answer = ' . $whatever . ';');
print($answer);
Kibbee
This will always create a syntax error as you forgot to add a ; after $whatever in the string that is eval'd
lamas
thanks, updated my code.
Kibbee
+7  A: 

Evaluate as PHP expression, but first check if it contains only digits and operators and space, and suppress any errors.

if (preg_match('/^[\d\+\-\/\*\s]+$/', $s)) {
  @eval('$result = ' . $s . ';');
}
Leventix
Don't forget the ; after eval and inside it, too.
lamas
Let's have a code competition to see who can write dangerous code consisting of only digits and mathematical operators. Is it possible?
Kibbee
using $result inside a double quoted (") string will cause PHP to try and replace the $result variable before evaluating the expression.
Kibbee
In order to make PHP evaluate the expression you'd have to write a valid PHP expression, but you can have only integer operands, and therefore all operators are mathematical. So if it is a valid expression, it will evaluate to an integer with no side effects.
Leventix
Sorry, I corrected all the mistakes.
Leventix
+1 for courage to suggest use of eval() on SO
kb