how do i make a user-input math expresstion

Discussion in 'PHP' started by rhythmiccycle, Oct 31, 2007.

  1. #1
    I'm a math teacher, I've made an online homework submission page. I want students to be able to submit answers, and then use php to check their answers, and give them a grade.

    I can check answers that are numbers, like "2", "-9" or "12.35".

    But I also want to check answers that are equations. on one problem the answer was "2a + 50", to check it i took in the user input as a string, and then I wrote out all different ways of writing it. Such as "50 + 2a", "a2 + 50" etc...

    I want to be able to take a user-input as an expression. for example if I was in the code and I wrote:

    $a = 1.2 // any number, just to give $a a numeric value
    2*$a + 50 == 50 + $a*2

    It would return true.

    But i only know how to take user input as strings or numbers, for example:

    $a = 1.2
    "2*$a + 50" == 50 + $a*2

    It would return false because the left side is a string.


    It would be possable to take the user input as a string and "explode" it into an array then make it into an expression, but that would be alot of work. I'm hoping there's a better way, or maybe someone already made a function i can use.


    how do i make a user-input math expresstion?

    please help
     
    rhythmiccycle, Oct 31, 2007 IP
  2. Barti1987

    Barti1987 Well-Known Member

    Messages:
    2,703
    Likes Received:
    115
    Best Answers:
    0
    Trophy Points:
    185
    #2
    
    <?php
    $v = '1'; //set v to 1 for eaiser computation
    $argument = '2*$a + 50 == 50 + $a*2';
    
    list($left,$right) = explode('==',$argument);
    
    /* right side */
    $finalright = keep_braking($right);
    
    $finalleft = keep_braking($left);
    
    if($finalright == $finalleft ){ echo 'correct';}else{echo 'incorrect';}
    ?>
    
    PHP:
    I might write the keep_braking for you tomorrow.

    Peace,
     
    Barti1987, Oct 31, 2007 IP
  3. rhythmiccycle

    rhythmiccycle Guest

    Messages:
    9
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    0
    #3
    thanks azizny,

    It looks like you are saying there is no simple way of doing it, a function that explodes the string and looks for each operator is needed. I was hoping there was a better way. but if you actually write the "keep_braking" I would really appreciate it.
     
    rhythmiccycle, Nov 1, 2007 IP