Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
384 views
in Technique[技术] by (71.8m points)

html - php check to see if variable is integer

Is there a nicer way to do this?

if( $_POST['id'] != (integer)$_POST['id'] )
    echo 'not a integer';

I've tried

if( !is_int($_POST['id']) )

But is_int() doesn't work for some reason.

My form looks like this

<form method="post">
   <input type="text" name="id">
</form>

I've researched is_int(), and it seems that if

is_int('23'); // would return false (not what I want)
is_int(23);   // would return true

I've also tried is_numeric()

is_numeric('23'); // return true
is_numeric(23); // return true
is_numeric('23.3'); // also returns true (not what I want)

it seems that the only way to do this is: [this is a bad way, do not do it, see note below]

if( '23' == (integer)'23' ) // return true
if( 23 == (integer)23 ) // return true
if( 23.3 == (integer)23.3 ) // return false
if( '23.3' == (integer)'23.3') // return false

But is there a function to do the above ?


Just to clarify, I want the following results

23     // return true
'23'   // return true
22.3   // return false
'23.3' // return false

Note: I just figured out my previous solution that I presented will return true for all strings. (thanks redreggae)

$var = 'hello';
if( $var != (integer)$var )
    echo 'not a integer';

// will return true! So this doesn't work either.

This is not a duplicate of Checking if a variable is an integer in PHP, because my requirements/definitions of integer is different than theres.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

try ctype_digit

if (!ctype_digit($_POST['id'])) {
    // contains non numeric characters
}

Note: It will only work with string types. So you have to cast to string your normal variables:

$var = 42;
$is_digit = ctype_digit((string)$var);

Also note: It doesn't work with negative integers. If you need this you'll have to go with regex. I found this for example:

EDIT: Thanks to LajosVeres, I've added the D modifier. So 123 is not valid.

if (preg_match("/^-?[1-9][0-9]*$/D", $_POST['id'])) {
    echo 'String is a positive or negative integer.';
}

More: The simple test with casting will not work since "php" == 0 is true and "0" === 0 is false! See types comparisons table for that.

$var = 'php';
var_dump($var != (int)$var); // false

$var = '0';
var_dump($var !== (int)$var); // true

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...