Number that should not appear

Asked

Viewed 42 times

2

I’m a beginner in PHP and need a little help.

I am making a very stupid system that performs the sum of two numbers, with this, when the user does not type anything correct and inform him that it needs to be typed two number to calculate the sum, I was able to do this, but it appears a 0 in front of the message, notice:

inserir a descrição da imagem aqui

    <?php
    error_reporting(0);
    if($_POST){
        $num1 = $_POST ['campo1'];
        $num2 = $_POST ['campo2'];
        echo $num1 + $num2;

        if($num1 <= 0 && $num2 <= 0) {
            echo "Numero invalido!";
        }
    }

?>

2 answers

3


In your code, you should check if one or the other number is less than or equal to 0, and not both. The if with the operator && will only be met if both conditions are valid, while the operator || will validate either one or the other. Then you put the result of the sum into one else, if one or other condition does not meet the criteria:

<?php
error_reporting(0);
if($_POST){
   $num1 = $_POST ['campo1'];
   $num2 = $_POST ['campo2'];

   if($num1 <= 0 || $num2 <= 0) {
      echo "Número inválido!";
   }else{
      echo $num1 + $num2;
   }
}
  • Thank you very much for your young help, I totally understood your logic regarding operators. After inserting on an Else in the correct structure it worked perfectly. Tks a Lot!

0

The problem is on line 6 echo $num1 + $num2;, you have him print out the sum of $num1 + $num2 and then print Invalid Number...

  • Hi, thanks for trying to clear my doubt, I appreciate it! I’m trying to understand your concept, but for me it didn’t make sense because I requested to print the Invalid Number of $num1 <= 0 && $num2 <= 0, you know what I mean..

Browser other questions tagged

You are not signed in. Login or sign up in order to post.