5

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?

Tyler
  • 21,762
  • 11
  • 61
  • 90
Tom
  • 1,068
  • 2
  • 25
  • 39

2 Answers2

7

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 . ';');
}
Sinan Ünür
  • 116,958
  • 15
  • 196
  • 339
Leventix
  • 3,789
  • 1
  • 32
  • 41
  • Don't forget the ; after eval and inside it, too. – lamas Feb 06 '10 at 13:28
  • 1
    Let's have a code competition to see who can write dangerous code consisting of only digits and mathematical operators. Is it possible? – Kibbee Feb 06 '10 at 13:30
  • using $result inside a double quoted (") string will cause PHP to try and replace the $result variable before evaluating the expression. – Kibbee Feb 06 '10 at 13:45
  • 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 Feb 06 '10 at 13:48
2

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
  • 65,369
  • 27
  • 142
  • 182
  • This will always create a syntax error as you forgot to add a ; after $whatever in the string that is eval'd – lamas Feb 06 '10 at 13:33