Pro.Luv Posted March 22, 2009 Share Posted March 22, 2009 Hi, I have this code that works fine, the problem is the code only works if Im adding numbers $sum = "1 + 1 + 1"; function str2num($Str) { $numTotal = 0; if ( $Nums = explode('+', $Str) ) { foreach ( $Nums as $Num ) $numTotal += $Num; return $numTotal; } else return 0; } print(str2num($sum)); I need this to work for any type of sum like: $sum = "1 + 1 + 5 - 2 * 2"; please help Thanks ! Quote Link to comment Share on other sites More sharing options...
WolfRage Posted March 22, 2009 Share Posted March 22, 2009 Then you need to expand your if statements to explode on any mathmatical symbols that you wish to support and they have to be in the proper mathmatical order. For instance by order of precedence you need to multiple prior to adding so explode around the multiplication and grab the last number of the first string and the first number of the second string and multiple. There are a lot of possibilities that you are going to have to code for. Good luck! Quote Link to comment Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.