Jump to content

print()


Pro.Luv

Recommended Posts

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 !

 

 

 

 

 

 

 

 

 

 

Link to comment
https://forums.phpfreaks.com/topic/150581-print/
Share on other sites

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!

Link to comment
https://forums.phpfreaks.com/topic/150581-print/#findComment-790960
Share on other sites

Archived

This topic is now archived and is closed to further replies.

×
×
  • 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.