Home > Mobile >  im currently learning php and my if statements do not work
im currently learning php and my if statements do not work

Time:01-30

<?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

CodePudding user response:

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 operation\n";
    $operator = readline("Which operator would you like to use? ( , -, %): ");
}

$number1 = readline('First number: ');

while(!(is_numeric($number1))) {
    echo "'$number1' is not a number\n";
    $number1 = readline('First number: ');
}

$number2 = readline('Second number: ');

while (!(is_numeric($number1))) {
    echo "'$number1' is not a number\n";
    $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);
}
?>

CodePudding user response:

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

  • Related