Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP math - operators

Tags:

php

math

So I have a simple site that is using php to do some simple math like so:

<form action="" method="POST">
<input type="text" name="first" />
<select name="method">
    <option>+</option>
    <option>_</option>
    <option>*</option>
    <option>/</option>
</select>
<input type="text" name="second" />
<input type="submit" value="Equals" />

The site lets the user inputs two numbers and then select a math operator to manipulate them by. So for example in the first input, the user could enter the number 3, select the subtraction operator, enter the number 1 in the next field and submit. I process the information like so:

if (isset($_POST['first']) && isset($_POST['second'])) {
   $first = $_POST['first'];
   $second = $_POST['second'];
   $method = $_POST['method'];
} 

However, I want to echo the result of the math problem on webpage after submitting. How would I do this? Just echoing all the variables would just give me (in this case) "3-1" instead of the actual answer which would be "2".

Any idea how would accomplish this?

like image 904
codedude Avatar asked Mar 27 '26 23:03

codedude


2 Answers

if (isset($_POST['first']) && isset($_POST['second'])) {
    $first = $_POST['first'];
    $second = $_POST['second'];
    $method = $_POST['method'];
    switch($method)
    {
        case '+':
            $result = $first + $second;
            break;
        case '-':
            $result = $first - $second;
            break;
        case '*':
            $result = $first * $second;
            break;
        case '/':
            // check for division by 0 (wouldn't want to blow anything up)
            $result = $first / $second;
            break;
        default:
            $result = 'undefined operation';
            break;
    }
    printf("%.5f %s %.5f = %s", $first, $method, $second, $result);
}

You need to use a switch statement on your $method like so:

switch($method){

    case '+':
        $result = $first + $second;
        break;

    case '-':
        $result = $first - $second;
        break;

    case '*':
        $result = $first * $second;
        break;

    case '/':
        $result = $first / $second;
        break;

}
var_dump($result);

Alternatively, you could also EVAL the operation:

$code = '$result = '.$first.$method.$second.';';
exec($code);
var_dump($result);

Note that you don't check for your input, it could lead to security issues:

if(!isset($_POST['first']) || !is_numeric($_POST['first'])){ exit('Bad number in #1'); }

Do the same for other input such as first, second and method :)

like image 26
Mathieu Dumoulin Avatar answered Mar 29 '26 11:03

Mathieu Dumoulin