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
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'] ) )
Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.