PHP - Comparing information

Asked

Viewed 1,212 times

1

I’m trying to compare the number inserted 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, some idea?

  • The two variables are from the same datatype?

  • I believe so. I am comparing only whole numbers.

  • checked the point and comma on line 2?

  • In $campo1 = $_POST['um'] missing a ; in the end.

  • I just forgot to put it in, but the original code is ;

  • 1

    The problem does not seem to be the code but the values ... var_dump() in doubt!

  • 1

    In its original code the condition would not be with === ? Because in case the 1 of $campo1 is string and that of $valor1 is whole... here for me your code works as it is, I think because you are with ==...

Show 2 more comments

3 answers

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.

You probably have === in condition (but of course it may be something else wrong in the original code).

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

However, if you change the condition to === It’ll be a mistake, look here at Ideone.

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

string '1' (length=1)
int 1

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

Of PHP manual:

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

Detail: The accepted answer would work even with the comparator ===, because it turned the string into integer with (int), which is unnecessary in the case, for being using ==.

1


It worked for me, I went through the code:

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

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

    echo $msg;
?>
  • It worked! Thank you very much.

1

If to compare string, use strcmp:

echo strcmp($campo1, $campo1);

Browser other questions tagged

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