Solved

PHP arithmatic problem

Posted on 2011-03-02
28
246 Views
Last Modified: 2012-05-11
hello,

I seem to be having a problem with getting php to calculate an equasion.
below is the code I have thus far!

the reason I am using arrays is that the values and operators are passed down from a form.
although my code shows the arrays statically defined, it should work the same.

the code I have creates the equasion but wont process it and output the answer.
I have tried using eval() and it still just outputs the formulae, not the answer.

below is the complete code:


<?

// the scores are kept in an array because there could be any number of scores
$scores=array("10","20","30","40");
// the operators are kept in an array because the formulae might call for any number of operators.
$operators=array(" * "," / "," - ","+");

// parses everything into a string.
//explode is not used because I dont want a delimeter between the chars and explode requires a delimeter
$i = 0;
while ($i <= 10) {
   
    $calcstring = $calcstring.$scores[$i].$operators[$i];
   
    $i++;  
}

//gets the lenth of the whole string
$formulaelenth =  strlen($calcstring);

// prints the formulae, where it should print the answer
$finalformulae = substr($calcstring, 0, -1);  // returns "abcde"
//eval("\$finalstring = \"$finalformulae\";");

echo "$finalstring";

?>

please can someone tell me where I am going wrong.

thanks,

regards,

Gavin
0
Comment
Question by:GPB1983
  • 13
  • 12
  • 3
28 Comments
 
LVL 34

Expert Comment

by:Beverley Portlock
Comment Utility
You need one more number than you have operators otherwise you will get

10 * 20 / 30 - 40 +

and you use finalString when the last variable is finalformulae
0
 
LVL 108

Expert Comment

by:Ray Paseur
Comment Utility
Add error_reporting(E_ALL) to the top of the script -- it may show you some surprising things!
0
 
LVL 34

Expert Comment

by:Beverley Portlock
Comment Utility
One other point eval evaluates PHP code, not formulae, so

   echo eval("10 + 20");

will produce nothing, whereas

   echo eval("echo 10 + 20");

would return 30


0
 

Author Comment

by:GPB1983
Comment Utility
hi, thanks for the quick reply

I start off with 4 operators and 4 values, I need to remove 1 operator, so it would computer,
other wise it would read as:
10 * 20 / 30 - 40 +, where as it should read as 10 * 20 / 30 - 40, as this is the formulae as it would be inserted into a calculator.

0
 
LVL 108

Expert Comment

by:Ray Paseur
Comment Utility
Install this and run it.  You can see it on my server here: http://www.laprbass.com/RAY_temp_gavin.php
<?php // RAY_temp_gavin.php
error_reporting(E_ALL);

// the scores are kept in an array because there could be any number of scores
$scores=array("10","20","30","40");
// the operators are kept in an array because the formulae might call for any number of operators.
$operators=array(" * "," / "," - ","+");

// parses everything into a string.
//explode is not used because I dont want a delimeter between the chars and explode requires a delimeter
$i = 0;
while ($i <= 10) {

    $calcstring = $calcstring.$scores[$i].$operators[$i];

    $i++;
}

//gets the lenth of the whole string
$formulaelenth =  strlen($calcstring);

// prints the formulae, where it should print the answer
$finalformulae = substr($calcstring, 0, -1);  // returns "abcde"
//eval("\$finalstring = \"$finalformulae\";");

echo "$finalstring";

var_dump($calcstring);

eval('$k = ' . $calcstring . '0' . ';');
var_dump($k);

Open in new window

0
 
LVL 108

Expert Comment

by:Ray Paseur
Comment Utility
Can you please tell us why you are designing an app this way?  If we could see the "50,000-foot" view we might be able to suggest a better way to approach the problem.
0
 
LVL 34

Expert Comment

by:Beverley Portlock
Comment Utility
"I start off with 4 operators and 4 values, I need to remove 1 operator, so it would computer,"

Make your last operator a space or a semi colon
0
 

Author Comment

by:GPB1983
Comment Utility
the reason I am designing it this way is that it is part of an app that prioritises jobs, the user input is a numreric value and an operator.
0
 

Author Comment

by:GPB1983
Comment Utility
bportlock,

please explain how that would effect the result. as I fail to understand.

thanks, regards,
gavin
0
 
LVL 108

Expert Comment

by:Ray Paseur
Comment Utility
Not sure I understand why a user would need to tell you a formula to compute the number for the priority.  Have you seen a design like this somewhere else?  If you can show us an example maybe we can tell you how it is being done.  Just a thought...
0
 

Author Comment

by:GPB1983
Comment Utility
the values come from a number of drop down menus, each that contain the value and the operator, such as;

25+, which would mean the value was 25 and the operator is +.

regards,

Gavin
0
 
LVL 108

Expert Comment

by:Ray Paseur
Comment Utility
Regarding this,

I start off with 4 operators and 4 values, I need to remove 1 operator, so it would computer,
other wise it would read as:
10 * 20 / 30 - 40 +, where as it should read as 10 * 20 / 30 - 40, as this is the formulae as it would be inserted into a calculator.


Do you always have "n" operators and "m" numbers?  Are "n" and "m" expected to be 4?  Could you have a condition with 3 numbers and 5 operators or 5 numbers and 3 operators?  What would you do then?  It's those kinds of questions that you might want to think about now before you release this code into the wild.  As you can see in the example posted at http:#35020074 you can add a zero to the end if the last operator is + or - but if you needed a multiplicative identity because the last operator was multiplication or division or exponentiation you would need to use 1.

If you want to remove the last element of an array, you can use this function.  But that would only make sense if you knew that the last operator in the array was extraneous.  And if it was extraneous, why even have it in the first place?
http://us2.php.net/manual/en/function.array-pop.php

0
 
LVL 108

Expert Comment

by:Ray Paseur
Comment Utility
25+, which would mean the value was 25 and the operator is +.

That is very helpful information.  Since the information is coming from an HTML form, it is by definition tainted and must be filtered on the server side after the form is submitted.  Please show us the form, and I am sure we can show you a safe way to process it.  The results will probably be simpler than what we are looking at now!
0
 

Author Comment

by:GPB1983
Comment Utility
the number of operators and values can be less than  6 but no more. for each value, the operators can be any arithamtical operator.

regards,

Gavin
0
IT, Stop Being Called Into Every Meeting

Highfive is so simple that setting up every meeting room takes just minutes and every employee will be able to start or join a call from any room with ease. Never be called into a meeting just to get it started again. This is how video conferencing should work!

 
LVL 108

Expert Comment

by:Ray Paseur
Comment Utility
Please show us an example of the form, thanks.
0
 

Author Comment

by:GPB1983
Comment Utility
I  can create the equasion, but php reads it as a string, instead of an equasion. an example of how it reads is:
$var 1 = 10
$var 2 = 12
$op = "+"

$var1.$op.$var2    reads as 10+12, where as it should read as 22.

regards,

gavin
0
 

Author Comment

by:GPB1983
Comment Utility
an exmaple of the form is:

$weighting = "070";
$weighting2 = "072";
$weighting3 = "074";

$thing = "+";
$thing2 = "-";
$thing3 = "*";



echo "<select name='score' size=4 multiple>";
      echo ("<option value=\"$criteria$weighting$thing\">$criteria</option>");
      echo ("<option value=\"$criteria2$weighting2$thing2\">$criteria2</option>");
      echo ("<option value=\"$criteria3$weighting3$thing3\">$criteria3</option>");
      echo "</Select>";

it then passes it down further where the formulae is calculated

regards,

gavin
0
 
LVL 108

Expert Comment

by:Ray Paseur
Comment Utility
OK, what is the value for $criteria, $criteria2, $criteria3?  They seem to be undefined.
0
 

Author Comment

by:GPB1983
Comment Utility
$criteria1,2 and 3 are text, they dont factor into the formulae, but in the interest of calrification, their values are:

"statement present"
"Image made"
"triage passed"

regards,

gavin
0
 
LVL 108

Expert Comment

by:Ray Paseur
Comment Utility
OK, thanks.  Where do these strings and values come from?  Are they in a data base?  I'm asking because we would want to have them embedded in both the form script and action script.  In a moment I'll show you how this might be able to work.
0
 

Author Comment

by:GPB1983
Comment Utility
yes they are from a database. I just used defined variables for testing purposes.

thanks
regards,
gavin
0
 
LVL 108

Expert Comment

by:Ray Paseur
Comment Utility
Let's see if this is starting to make sense.  Mostly I copied what you posted here.  Is this the sort of thing you envision?  Install it and run it to see the moving parts.
<?php // RAY_temp_gavin_2.php
error_reporting(E_ALL);
echo "<pre>";

// DATA DEFINITIONS FROM THE POST AT EE
$weighting = "070";
$weighting2 = "072";
$weighting3 = "074";

$thing = "+";
$thing2 = "-";
$thing3 = "*";

$criteria = "statement present";
$criteria2 = "Image made";
$criteria3 = "triage passed";

// SHOW THE POST ARRAY, IF ANY
if (!empty($_POST))
{
    var_dump($_POST);
}

// PUT UP THE FORM
echo '<form method="post">';
echo "<select name='score[]' size=4 multiple='multiple'>";
echo ("<option value=\"$criteria$weighting$thing\">$criteria</option>");
echo ("<option value=\"$criteria2$weighting2$thing2\">$criteria2</option>");
echo ("<option value=\"$criteria3$weighting3$thing3\">$criteria3</option>");
echo "</select>";
echo '<input type="submit" />';
echo '</form>';

Open in new window

0
 

Author Comment

by:GPB1983
Comment Utility
hello,

I have ran that script and yes, that is exactly what I am trying to create, it would have a maximum of 6 menus, my prototype had one, just so I could get it working.

my prototype can get the 074* part of the code, but when link more than one value, it displays the result as a string, instead of the answer.

thanks,
regards,
gavin
0
 
LVL 108

Expert Comment

by:Ray Paseur
Comment Utility
I'm still trying to get the rules straight here.  Will 074 always be associated with *?  Or to put it another way, if this information is coming from your data base, what are the relationships that determine the values in the $criteria, $weighting, $thing variables?
0
 

Author Comment

by:GPB1983
Comment Utility
074 is just a value that I am using.

contents of the menu will all come from an array, the value would be made from 2 values concatinated together.

echo ("<option value=\"$criteria3$weighting3$thing3\">$criteria3</option>");

$criteria would be the criteria that the user would select
£weighting and $thing would be the value passed down

so if 2 options where selected, they would be:

74+
72*

(the numbers can be any value, I am using them for testing purposes.)

what I tried to do was to concatinate the 2 values together, so they would read as:
74+72*, trimming off the last char, which would mean the equasion would be 74+72. it concatinates fine, but it only outputs the formulae, I need the resilt, which in this example would be 146.

thanks,
regards,
gavin

regards.

gavin
0
 
LVL 108

Accepted Solution

by:
Ray Paseur earned 500 total points
Comment Utility
I may not have thought to recommend it before, but please consider getting this book and working through the examples.  It will not make you a pro, but it will be an enjoyable and informative experience.  Great explanations, great examples, and a downloadable code library that you can copy and modify for your own apps.
http://www.sitepoint.com/books/phpmysql4/

Computer programming is a fairly precise craft.  When you say, "...made from 2 values concatinated together" and then post something like this it gives me pause.
echo ("<option value=\"$criteria3$weighting3$thing3\">$criteria3</option>");
As you can see there is no instance in that line of having two values concatenated.  It may not seem important, but it is this kind of thinking that causes a lot of unfortunate lost time.

Regarding this part of things:
74+
72*
You do understand that the order of these strings matters to the output of the math, right?  In one order you would have 74+72, however in the other order you would have 72*74.  

Here is a code snippet that shows how to evaluate the string.  It is quite similar to the snippet I posted above at http:#35020074

I think I will leave this question with that.  I do not understand your application design, and I've seen a lot of applications and studied a lot of user-interfaces.  This just does not sound like a technically competent design.  If you're going to depend on this app to do something important, you might want to step back from it and hire a professional software developer.  Best of luck, ~Ray
<?php // RAY_temp_gavin_3.php
error_reporting(E_ALL);
echo "<pre>";

// A STRING OF THE SORT WE MIGHT GET FROM AN EXTERNAL SOURCE
$str = '74+72*';

// HOW TO REMOVE THE RIGHTMOST CHARACTER
$str = substr($str, 0, -1);
var_dump($str);

// HOW TO EVALUATE THE STRING
eval('$k = ' . $str . ';');
var_dump($k);

Open in new window

0
 

Author Comment

by:GPB1983
Comment Utility
Ray,

thanks for all your help, I think I have narrowed down the problem, basically php doesnt like if you store a mathematicald operator in a variable,

it likes
$var1 = 10;
$var2 = 20;
$sumof = $var1 + $var2

it dislikes
$var1 = 10;
$var2 = 20;
$var3 = "+";
$sumof = $var1 .$var3. $var2

or

$sumof = $var1 $var3 $var2

which is what I was trying to do. I have sorted it all now, basically I have multiple menus, where the suer can select multiple values, they are stored in arraysd, those arrays are merged into a single array and then I use array_sum to get the result. so I have something workable!

thanks for all the help, it pointed me in the right direction

here is the url working as it should be:
http://www.gavinbuczko.co.uk/alpha.php

thanks again mate,

regards, Gavin
0
 

Author Closing Comment

by:GPB1983
Comment Utility
very thorough and helpful solutions. :-)
0

Featured Post

How your wiki can always stay up-to-date

Quip doubles as a “living” wiki and a project management tool that evolves with your organization. As you finish projects in Quip, the work remains, easily accessible to all team members, new and old.
- Increase transparency
- Onboard new hires faster
- Access from mobile/offline

Join & Write a Comment

Developers of all skill levels should learn to use current best practices when developing websites. However many developers, new and old, fall into the trap of using deprecated features because this is what so many tutorials and books tell them to u…
This article discusses four methods for overlaying images in a container on a web page
Explain concepts important to validation of email addresses with regular expressions. Applies to most languages/tools that uses regular expressions. Consider email address RFCs: Look at HTML5 form input element (with type=email) regex pattern: T…
The viewer will learn how to look for a specific file type in a local or remote server directory using PHP.

763 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

10 Experts available now in Live!

Get 1:1 Help Now