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
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
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

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