PHP - Comparing information [closed]

1

I'm trying to compare the number entered in the textbox with a number defined in the variable, like this:

<?php
 $campo1 = $_POST['um'];
 $valor1 = 1;

   if($campo1 == $valor1){
      $msg="ok";
   }
   else{
      $msg="erro";
   }

?>

Textbox:

<div class="6u"><input type="text" name="um" class="text" placeholder="Primeiro número" /></div>

But always returns false, any ideas?

    
asked by anonymous 07.01.2016 / 15:11

3 answers

1

Here for me it worked, I moved the code:

<?php
    $campo1 = $_POST['um'];
    $valor1 = 1;
    $msg = "erro";

    if(( int ) $campo1 == $valor1){
       $msg = "ok";
    }

    echo $msg;
?>
    
07.01.2016 / 15:31
3

The problem is with the original code, which is certainly not the same as the question, since the question code works perfectly the way it is .

It should probably be with === in the condition (but of course it may be something else wrong in the original code).

See in the Ideone an example with the code of the question (taking the value that would be obtained by post ) with the string "1" in variable $campo1 .

However, if you change the condition to === it will already give you an error, see here on Ideone .

As the @rray suggested in the comment, see var_dump of variables (in this case sent by post through input type="text" , just as it is in the question code):

string '1' (length=1)
int 1

This happens because the input field of type="text" always sends a string (even if it is a number), while the declaration of the $valor1 variable is as an integer, and the === comparator requires that the values are identical , including the type.

PHP manual :

$a === $b   // Idêntico Verdadeiro (TRUE) se $a é igual a $b, e eles são do mesmo tipo.

Detail: The accepted response would work even with the === comparator, because it has transformed the string to integer with (int) , which is unnecessary in this case because it is using == .

    
07.01.2016 / 16:05
1

If it is to compare string, use strcmp:

echo strcmp($campo1, $campo1);

    
07.01.2016 / 15:50