skip to Main Content
<?php

$operation = readline('which operation do you want to use? (+, -, %) ') . PHP_EOL;

if ($operation != '+' || $operation != '-' || $operation != '%' ) {
    echo " '$operation' is not a valid operation"; 
} 

$number1 = readline('First number? ') . PHP_EOL;

if ($number1 != is_numeric($number1)) {
    echo " '$number1' is not a number ";
}

$number2 = readline('Second number? ') . PHP_EOL;



if ($operatie == '+') {
    echo 'Your result is:' . $number1 + $number2;  
}

if ($operatie == '-') {
    echo 'Your result is: ' . $number1 - $number2;    
}

if ($operatie == '%') {
    echo 'Your result is: ' . $number1 % $number2;
}
?>

i expected this to be a working calculator but i don’t know how to fix i would really appreciate it if you can fix it for me

2

Answers


  1. The issue is with your first condition, you have to use && instead of || because like this execution will always fall inside the if statement

    Login or Signup to reply.
  2. I fixed your code, it is broken in many places
    You need a while loop for the operator validation and for checking if input is numeric, also you can’t use an if statment for this
    The last part where you print out the answers, you just can’t concat the calculations to the str, it will result in an error
    If you have any questions about the code I wrote feel free to ask

    <?php
    
    $operator = readline("Which operator would you like to use? (+, -, %): ");
    
    while(!($operator == '+' || $operator == '-' || $operator == '%')) {
        echo "'$operator' is not a valid operationn";
        $operator = readline("Which operator would you like to use? (+, -, %): ");
    }
    
    $number1 = readline('First number: ');
    
    while(!(is_numeric($number1))) {
        echo "'$number1' is not a numbern";
        $number1 = readline('First number: ');
    }
    
    $number2 = readline('Second number: ');
    
    while (!(is_numeric($number1))) {
        echo "'$number1' is not a numbern";
        $number2 = readline('Second number: ');
    }
    
    if ($operator == '+') {
        echo 'Your result is: ' . strval($number1 + $number2);  
    }
    
    if ($operator == '-') {
        echo 'Your result is: ' . strval($number1 - $number2);    
    }
    
    if ($operator == '%') {
        echo 'Your result is: ' . strval($number1 % $number2);
    }
    ?>
    
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search