0

So lets show an example here shall we?

Let's say I have 2 strings that are like this....

$math1 = "+300";
$math2 = "-125";

So obviously the answer would have to be +175 but how do I actually do the math while the input is a string.

I can't simply do

$math1 - $math2

Because it'd have to figure out if it is a + or a -, so how can this exactly be done?

Cameron Swyft
  • 448
  • 2
  • 6
  • 21
  • 2
    You have to know what number you're subtracting from what number: `$result = $math1 - abs($math2);` or `$result = $math1 + $math2;` – Mark Baker Nov 24 '15 at 00:42
  • Well the thing is, the operations could be different. It's data that would come from the database and come out as a string. So it could be -300 or +300 or even x300. – Cameron Swyft Nov 24 '15 at 00:44
  • so cast it as an integer if you're forced to using strings – Funk Forty Niner Nov 24 '15 at 00:45
  • Dupe of http://stackoverflow.com/questions/1015242/how-to-evaluate-formula-passed-as-string-in-php or http://stackoverflow.com/questions/5057320/php-function-to-evaluate-string-like-2-1-as-arithmetic-2-1-1 ? – fvu Nov 24 '15 at 00:46
  • 300 - (-125) = 425, whereas 300 - (125) = 175. both come back as `int`. php is a loose type language, it can do the math directly. simply `$math1 - $math2` return correct result – Andrew Nov 24 '15 at 00:49

3 Answers3

0

You can use intval to get the integer value of a variable, and then you can do basic math operations.

<?php
    $math1 = intval("+300");
    $math2 = intval("-125");
    echo $math1 - $math2;
?>
Rajdeep Paul
  • 16,887
  • 3
  • 18
  • 37
0
intval($math1) + intval($math2);   
Eduardo Escobar
  • 3,301
  • 2
  • 18
  • 15
0

Can be:

$result = abs($math1) - abs($math2);
Pao Im
  • 337
  • 3
  • 8