Jump to content

Check if string is integer problem


FraanXT

Recommended Posts

Hello guys, I have a form where you can select a score between 0 and 10(only integers).

I want to check if the value that I recive, is integer.

 

Im using this code(exemple):

$integer =  intval($_POST["p1"]);
    if(is_int($integer)){
        echo 'INT';
    } else {
        echo 'NO INT';
    }

My problem is that if it recive letters, the conversion converts it to 0, and it says that it is integer.

So with this method I should discard the 0.

 

You guys know a method to avoid that?

 

Thank you guys

Link to comment
https://forums.phpfreaks.com/topic/288890-check-if-string-is-integer-problem/
Share on other sites

Also wanted to mention that I see in your original code you are using intval. FYI ctype_digit expects a string argument, so if you are converting it to an integer type then you are going to get unexpected results from ctype_digit. So to be clear, do not cast/convert the value as an integer before using ctype_digit. Posted variables should always be a string type, so you don't need to do anything special before using ctype_digit, but if you really want to be explicit, type cast to string:

 

// this should be okay..
if ( ctype_digit( $_POST['p1'] ) ) 

// ..but if you want to be more explicit
if ( ctype_digit( (string) $_POST['p1'] ) )

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.