Arham Khan
Arham Khan

Reputation: 1

A non numeric value encountered in ..... on line 35

This is the code that I'm using. All the arithemetic operations are done successfully except subtraction. When Subtraction is selected, it gives the error. If I use two different echo statements, one for "The answer is: " and the other echo statement for the subtraction between two variables, it gives no error. What is the reason behind the generation of this error when both the variables string are printed using one echo statement??

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>Calculator</title>
</head>
<body>
    <form>
        <input type="text" name="num1" placeholder="First Number">
        <input type="text" name="num2" placeholder="Second Number">
        <select name="operator">
            <option>None</option>
            <option>Add</option>
            <option>Subtract</option>
            <option>Multiply</option>
            <option>Divide</option>
        </select>
        <br>
        <button name="submit" value="submit">Calculate</button>
    </form>

<?php 
    if (isset($_GET['submit'])) {
    $num1 = $_GET['num1'];
    $num2 = $_GET['num2'];
    $operator = $_GET['operator'];
    switch ($operator) {
            case "None":
                echo "You need to set a method!";
                break;
            case 'Add':
                echo "The answer is: ".$num1 + $num2;
                break;
            case 'Subtract':
                echo "The answer is: ".$num1 - $num2;
                break;
            case 'Multiply':
                echo "The answer is: ".$num1 * $num2;
                break;
            case 'Divide':
                echo "The answer is: ".$num1 / $num2;
                break;
        }   
    }
 ?>
</body>
</html>

Upvotes: 0

Views: 136

Answers (1)

bassxzero
bassxzero

Reputation: 5041

https://www.php.net/manual/en/language.operators.precedence.php

The . in your string concatenation has a higher operator precedence than your -. You should add parentheses around your $num expressions.

switch ($operator) {
    case "None":
        echo "You need to set a method!";
        break;
    case 'Add':
        echo "The answer is: ".($num1 + $num2);
        break;
    case 'Subtract':
        echo "The answer is: ". ($num1 - $num2);
        break;
    case 'Multiply':
        echo "The answer is: ".($num1 * $num2);
        break;
    case 'Divide':
        echo "The answer is: ".($num1 / $num2);
        break;
}   

Upvotes: 1

Related Questions