Validate string in number with php

Asked

Viewed 695 times

1

I come across the following situation. I have a string and have to validate its value. That way, I have to check if it is integer. Then I have to pass the string to number and check if it is integer or float.

I thought of something like this:

if((int)"13.1" == 13.1){
   echo "certo";        
}

The problem is whether it looks like true or false digital.

if((int)"true" == "true"){
    echo "certo";   
}

It is still possible, the person pass non-string value. How do I validate in this case. I need you to accept only integer, but many of the times I will receive this value in string, and I can receive in Boolean or float... How to validate in this situation?

1    = true
1.1  = false
true = false
"ss" = false

2 answers

4


  • 2

    This then will give problem if the person passes the string 0. A correct test would be if( $peso === false )

  • @Bacco Actually not only string, but also the number 0.

  • @abcd is that you mentioned that passes strings in the question, in fact GET never comes as a number, just so I didn’t go into details. But the important thing is that you understood the idea ;)

  • I ended up using the following: if(filter_var("0", FILTER_VALIDATE_INT, array("options" => array("min_range"=>0, "max_range"=>10))) === false) {echo "foi";} . ATT

2

Try using a native PHP test function

<?php

$var1 = "0";

if (is_int($var1)) {
  echo "OK";
}

?>

  • Marcolla, this function does not serve, because as said above, I get string, so I would have to know if float or int.

Browser other questions tagged

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