-1

last time i made simple calculator for my exercise, and its works good. but today when i open the codes again and run it in my browser, something strange happen. here is my html code:

<html>
<head>
<meta charset="utf-8">
<title>Calculator</title>
</head>
<body>
    <form method="post" action="disp_form.php">
        <p>First Value:<br/>
            <input type="text" id="first" name="first">
        </p>
        <p>Second Value:<br/>
            <input type="text" id="second" name="second">
        </p>
        <select method="post" name="group1">
            <option  name="group1" id="add" value="add"><p>+</p><br/>
            <option  name="group1" id="subtract" value="subtract"><p>-</p><br/>
            <option  name="group1" id="times" value="times"><p>x</p><br/>
            <option  name="group1" id="divide" value="divide"><p>/</p><br/>
        </select>
       <p></p>
       <button type="submit" name="answer" id="answer" 
           value="answer">Calculate</button>
    </form>
</body>
</html>

and this my php code

<?php
$first = $_POST['first'];
$second= $_POST['second'];
$operator = $_POST["group1"];
switch($operator)
{
    case "add":
        echo "Answer is: " .$first + $second;
        break; 
    case "subtract":
        echo "Answer is: " .$first - $second;
        break;
    case "times":
        echo "Answer is: " .$first * $second;
        break; 
    case "divide":
        echo "Answer is: " .$first / $second;
        break;
}
?>

the strange is, when i use / & *,the output is correct (eg 2*5, output is "Answer is: 10). but when i use + & -, the output is incorrect. (eg 8+5, output is 5, and for 8-5, output is -5) i thought the first value for add and substract defined as zero, thats why its result -5 and 5. but how the times and divide is done right?

litelite
  • 2,857
  • 4
  • 23
  • 33
principiorum
  • 528
  • 7
  • 21

5 Answers5

4

The multiplication and division operators have a higher precedence than the concatenation operator, so the mathematical operation is evaluated first for those cases, and then combined into the string.

In these cases, the code is equivalent to:

echo "Answer is: " .($first * $second);
echo "Answer is: " .($first / $second);

which gets you the correct answer.

The addition and subtraction operators have the same precedence, and are left associative, so the lines are executed like this:

echo ("Answer is: " . $first) + $second;
echo ("Answer is: " . $first) - $second;

In both cases, the initial string is type-cast to an integer, before the mathematical operation. Because the string does not start with a number, it is equivalent to writing

echo 0 + $second;
echo 0 - $second;

which results in either a positive or negative version of $second.

As other people have said, wrap the mathematical operations in brackets to ensure the expressions are evaluated in the right order. It will also make your code easier to read.

iainn
  • 16,826
  • 9
  • 33
  • 40
0

The problem is here

echo "Answer is: " .$first + $second;

First concatenation happening with Answer is: " .$first because of the dot you have added. you need to close bracket the addition and after need to concatenate with the string like following.

echo "Answer is: " . ($first + $second);

Same thing happening for subtraction also.

Thamaraiselvam
  • 6,961
  • 8
  • 45
  • 71
  • the code works with adding bracket, but why the divide and times dont need bracket to show the right answer? @Thamaraiselvam – principiorum Aug 14 '17 at 12:43
  • Because of [operator precedence](http://php.net/manual/en/language.operators.precedence.php). `*` and `/` have a higher precedence than `+`, `-` and `.`. – Phylogenesis Aug 14 '17 at 12:45
  • 1
    Please refer this answer https://stackoverflow.com/a/10841215/2975952 @mgibsonbr explained very clearly about operator precedences – Thamaraiselvam Aug 14 '17 at 12:45
0

The problem is it thinks you're doing string operations to add to the string output. At the simplest you could put the mathemetical operations in brackets. e.g.:

echo "Answer is: " .($first + $second);

or do them on a separate line into another variable, and then output the resulting variable instead. You could also convert them to floats to be extra-sure:

echo "Answer is: " .(floatval($first) + floatval($second));
ADyson
  • 57,178
  • 14
  • 51
  • 63
  • it does works sensei. now im curious about how the divide and times gave the correct answer without brackets.. @ADyson – principiorum Aug 14 '17 at 12:47
  • I would think because * and / have higher precendence so it doesn't attempt to append the first variable to the string _before_ it does the maths, which is what happens with + and -. If the answer has helped please don't forget to upvote / mark as accepted once the option is available - thanks :-) – ADyson Aug 14 '17 at 12:48
0

You need to put parenthesis around ($first + $second) to get the expected result. Multiplication and division operators have precedence over the addition and subtraction operators but in PHP the . to add strings is on the same level as addition and substraction which can lead to unexpected results. Source

Vyctorya
  • 1,387
  • 1
  • 12
  • 18
0

This is because addition and subtraction operators in PHP convert both values to int and then add them, to break it down the statement you have written is interpreted like this echo (int) ("Answer is: " .$first) + (int) ($second);

To correct this you should add/subtract first then concat like the following:

echo "Answer is: " .($first + $second);