Jump to content

How can check variable value content integer or not by is_int() ?


man12_patil3

Recommended Posts

I really don't understand why this thread has caused so much confusion. Reg expressions to check if a variable is an integer... really? Why?

Yeah, I know. But apparently an INT field type in the database isn't enough. And it's true that PHP doesn't have a function to check if a numeric string is strictly an integer.

 

If the field type is INT then what else could be returned except for a string containing an INT?

Link to comment
Share on other sites

I suppose:

$val = intval($val);
echo is_int($val);

 

Would work.

Actually no. If $val isn't a valid integer then intval() will return 0. It always returns an integer so is_int(intval($variable)) is always true.

 

That's pretty annoying. I would say check if the value was 0 but 0 itself is a possible integer. Seems like you would have to check if the variable was 0 then echo intval.

 

Seems overcomplicated. I'll stick to not using 0 as an integer.

Link to comment
Share on other sites

I really like Pikachu's solution (modified slightly)

 

<?php 

$values = array( 15.1, -20, '4524', 15, 'zomg', '-434', '12.5', '--10' );

foreach( $values as $v ) {
var_dump($v);
echo ( isInt($v) ? '<font color="green">is ' : '<font color="red">is not ' ).' an integer or integer string</font><br>';
}

function isInt( $n ) {
$n = (string) $n;
return ctype_digit($n[0]=='-'?substr($n,1):$n);
}

?>

 

Or one line

return ctype_digit( substr($n,0,1)=='-'?substr($n,1):(string)$n );

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.