Validate string in number with php

0

I came across the following situation. I have a string and I have to validate its value. That way, I have to check if it's integer. So I will 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 digital or true is true.

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

It is still possible, the person passing non-string value. How do I validate in this case. I need to accept only integer, but many 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
    
asked by anonymous 10.07.2016 / 22:18

2 answers

3

You can use the filter_input function. Here is an example:

$peso = filter_input(INPUT_GET, 'peso', FILTER_VALIDATE_INT);
if (!$peso) {
   echo 'Valor inválido.';
}

More examples here: link

(Edit) There are more legal explanations of filters here too: link

    
10.07.2016 / 22:30
1

Try using a native PHP test function

<?php

$var1 = "0";

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

?>
    
10.07.2016 / 22:29